简体   繁体   中英

jQuery select LI above element

I'm trying to select the list item above a button and change its parent's background-color to red.

    <li>red bg on click <input class="addtocart" value="press" name="button"></li>
    <li>red bg on click <input class="addtocart" value="press" name="button"></li>
    <li>red bg on click <input class="addtocart" value="press" name="button"></li>
    <li>red bg on click <input class="addtocart" value="press" name="button"></li>

jQuery so far:

$(document).ready(function() {
  $(".addtocart").click( function(){
     $('li').parent().css('background-color', 'red');
  });
});

From what I can see it looks correct, but it seems to be changing a different element's background-color .

Thanks

this

$(this).parent().css('background-color', 'red');

Try:

$(document).ready(function() {

      $(".addtocart").click( function()
           {
             $(this).closest('li').css('background-color', 'red');
           }
      );
});

Your selector is wrong . Try to use this for current element

When you use $('li') it will apply to all li elements

$(this).parent().c....

You need current clicked element

$(this).parent().css('background-color', 'red');

Demo: Fiddle

尝试更改为此:

$(this).parent().css('background-color', 'red');

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