[英]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. 我试图选择按钮上方的列表项,并将其父级的background-color
更改为红色。
<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: 到目前为止的jQuery:
$(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
. 从我所看到的来看,它看起来是正确的,但是它似乎正在更改其他元素的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 尝试将this
用于当前元素
When you use $('li')
it will apply to all li
elements 当您使用$('li')
,它将应用于所有li
元素
$(this).parent().c....
尝试更改为此:
$(this).parent().css('background-color', 'red');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.