【问题标题】:How do I make jQuery modify only one div, instead of all divs of the same class?如何让 jQuery 只修改一个 div,而不是同一类的所有 div?
【发布时间】:2009-01-01 19:08:15
【问题描述】:

我网站的每个页面都有 10 个(几乎)相同的 div,仅在文本中有所不同。当单击 div 的某个部分时,我希望修改该 div 的不同部分。

我正在使用此代码:

$(document).ready(function(){
 $(".notLogged img").mouseover(function(){
  $(this).parent()>$("span").html("You must be logged in to vote.");
 })
})

我认为这将按如下方式工作:对于“notLogged”分类 div 中的所有 img 元素,鼠标悬停会导致该 div 的不同部分发生变化。

但是,事实并非如此。每当触发鼠标悬停事件时,所有具有“notLogged”类的 div 都会被修改。

如何修改此代码,以便只修改鼠标悬停所在的 div?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    试试这样:

    $(document).ready(function(){
     $(".notLogged img").mouseover(function(){
      $(this).parent().find("span").html("You must be logged in to vote.");
     });
    });
    

    【讨论】:

      【解决方案2】:
      // Assuming the 1st span in the div is the one to be modified.
      $(this).parent().$('span:eq(1)').html("You must be logged in to vote.");
      // :eq(1) selects the first element that matches its selector.  You could
      // also use ':first' in this case.
      

      【讨论】:

      • 我认为 eq(1) 实际上会返回该元素的第二个实例,因为 jQuery 对象返回从索引 0 开始的元素。因此,eq(0) 将返回第一个元素。
      猜你喜欢
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多