如何让jQuery只修改一个div,而不是同一个类的所有div?

时间:2021-06-13 20:33:49

Each page of my site has 10 (almost) identical divs, varying only in the text within. When a certain part of a div is clicked, I want a different part of that div to be modified.

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

I'm using this code:

我正在使用此代码:

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

I thought this would work as follows: For all img elements within a "notLogged" classed div, a mouseover would cause a different part of that div to change.

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

However, that's not what happens. Whenever that mouseover event is triggered, all divs with the "notLogged" class are modified.

然而,这不是发生的事情。每当触发鼠标悬停事件时,都会修改具有“notLogged”类的所有div。

How can I modify this code so only the div in which the mouseover originated is modified?

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

2 个解决方案

#1


Try it like this:

试试这样:

$(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.

#1


Try it like this:

试试这样:

$(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.