简体   繁体   中英

How do I make jQuery modify only one div, instead of all divs of the same class?

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.

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.

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

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

Try it like this:

$(document).ready(function(){
 $(".notLogged img").mouseover(function(){
  $(this).parent().find("span").html("You must be logged in to vote.");
 });
});
// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM