繁体   English   中英

可以在Jquery中将变量用作后代选择器吗?

[英]Can you use variables as descendant selectors in Jquery?

我试图弄清楚如何在Jquery中使用变量制作选择器,如子代选择器。

我知道您可以使用.add()添加变量,但是我还无法弄清楚如何使用它们来缩小选择范围。

这是我一直在玩的游戏:

 //descendant selector using classnames: $("div.aReallyLongClassName li.anotherReallyLongClassName").css({background:"red"}); //Using the jquery below doesn't work, but the console displays the classnames exactly how they appear in the jquery above. var foo = 'div.aReallyLongClassName'; var bar = 'li.anotherReallyLongClassName'; $("#console").html('"' + foo + ' ' + bar + '"'); $('"' + foo + ' ' + bar + '"').css({background:"green"}); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="aReallyLongClassName"> <ul> <li>No background</li> <li class="anotherReallyLongClassName">Red BG = Fail, Green BG = Success!</li> </ul> </div> <div class="foobar"> <ul> <li>No background</li> <li class="anotherReallyLongClassName">No background</li> </ul> </div> Computed selector is: <span id="console"></span> 

如何在Jquery中使用变量选择后代?

您的报价过多

$(foo + ' ' + bar).css({background:"green"});

会做。 您的代码段已更新并呈绿色:

 //descendant selector using classnames: $("div.aReallyLongClassName li.anotherReallyLongClassName").css({background:"red"}); //Using the jquery below doesn't work, but the console displays the classnames exactly how they appear in the jquery above. var foo = 'div.aReallyLongClassName'; var bar = 'li.anotherReallyLongClassName'; $("#console").html('"' + foo + ' ' + bar + '"'); $(foo + ' ' + bar).css({background:"green"}); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="aReallyLongClassName"> <ul> <li>No background</li> <li class="anotherReallyLongClassName">Red BG = Fail, Green BG = Success!</li> </ul> </div> <div class="foobar"> <ul> <li>No background</li> <li class="anotherReallyLongClassName">No background</li> </ul> </div> Computed selector is: <span id="console"></span> 

改变这个

 $("#console").html('"' + foo + ' ' + bar + '"');

对此:

 $("#console").append(foo.html());
 $("#console").append(bar.html());

或对此:

$("#console").html(foo.html() + bar.html());

否则,您会将字符串(例如div.aReallyLongClassName )附加到$("#console")

另外,您可以创建jquery对象并按如下方式使用它们:

var foo = $('div.aReallyLongClassName');
var bar = $('li.anotherReallyLongClassName');

$("#console").append(foo);
$("#console").append(bar);

foo.css({background:"green"});

bar.css({background:"green"});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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