-1

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

4

5 回答 5

4

利用this

$(this).parent().css('background-color', 'red');
于 2013-06-12T11:17:37.680 回答
4

尝试:

$(document).ready(function() {

      $(".addtocart").click( function()
           {
             $(this).closest('li').css('background-color', 'red');
           }
      );
});
于 2013-06-12T11:18:07.317 回答
1

你的选择器是错误的。尝试this用于当前元素

当您使用 $('li')它时,它将适用于所有li元素

$(this).parent().c....
于 2013-06-12T11:18:01.300 回答
1

您需要当前单击的元素

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

演示:小提琴

于 2013-06-12T11:18:07.700 回答
1

尝试更改为:

$(this).parent().css('background-color', 'red');
于 2013-06-12T11:19:37.563 回答