我如何在 JQuery 中使用带有 "this" 的相邻兄弟选择器?
How can I use adjacent sibling selectors with "this" in JQuery?
我有一个包含相同 class 的各种 div
的列表。我正在使用 .each
函数来 select in dividual ones on the user click(仅作为示例),之后的任何操作自然需要 this
,因此只有 select 是有问题的 div。例如:
$(".div").each(function(){
$(this).click(function(){
$(this).css("background","green");
});
});
但是如果我想让行中的下一个元素在单击时也变成绿色怎么办?我的第一直觉是使用 adjacent sibling selectors,但似乎只有在使用两个绝对元素时才有效,即 $(".element1 + .element2")
。我似乎无法让它与 this
一起工作。
这里有一个 JSfiddle 有一个完整的例子可以玩。
我该怎么做?
为了 "make the next element in line turn green as well on the click",您必须添加到 jQuery 对象中的元素集。
您可以使用nextElementSibling MDN in correlation with jQuery's add
$(this).add(this.nextElementSibling).css("background", "green");
您正在寻找$(this).next()
http://jsfiddle.net/naad8wbr/3/
$(".div").click(function () {
$(this).next().css("background", "green");
});
如果你想要下一个和这个,那么你可以使用:
$(".div").click(function () {
$(this).next().andSelf().css("background", "green");
});
我有一个包含相同 class 的各种 div
的列表。我正在使用 .each
函数来 select in dividual ones on the user click(仅作为示例),之后的任何操作自然需要 this
,因此只有 select 是有问题的 div。例如:
$(".div").each(function(){
$(this).click(function(){
$(this).css("background","green");
});
});
但是如果我想让行中的下一个元素在单击时也变成绿色怎么办?我的第一直觉是使用 adjacent sibling selectors,但似乎只有在使用两个绝对元素时才有效,即 $(".element1 + .element2")
。我似乎无法让它与 this
一起工作。
这里有一个 JSfiddle 有一个完整的例子可以玩。
我该怎么做?
为了 "make the next element in line turn green as well on the click",您必须添加到 jQuery 对象中的元素集。
您可以使用nextElementSibling MDN in correlation with jQuery's add
$(this).add(this.nextElementSibling).css("background", "green");
您正在寻找$(this).next()
http://jsfiddle.net/naad8wbr/3/
$(".div").click(function () {
$(this).next().css("background", "green");
});
如果你想要下一个和这个,那么你可以使用:
$(".div").click(function () {
$(this).next().andSelf().css("background", "green");
});