使用变量作为 jQuery 类选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15008224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a variable as jQuery class selector
提问by Wottensprels
I know that this question was answered multiple times here on stackoverflow, but i just can't get it to work on my problem.
我知道这个问题在 stackoverflow 上被多次回答,但我无法解决我的问题。
What i want to do is, when a <label>
is clicked, check for the labels class and change all matching elements to backgroundColor : #000000
我想要做的是,当<label>
点击a 时,检查标签类并将所有匹配的元素更改为backgroundColor : #000000
Here is my code:
这是我的代码:
$(function() {
$('label').click(function(){
var group = this.className ;
$('label .'+group).css({
'backgroundColor' : '#000000'
}) ;
}) ;
});
Unfortunately, this just does nothing. It even throws no error. Where is my fault?
不幸的是,这没有任何作用。它甚至不会抛出任何错误。我的错在哪里?
Solution
解决方案
I had to remove the whitespace in the selector:
我不得不删除选择器中的空格:
$('label.'+group)
回答by
Maybe you should remove the whitespace in $('label .'+group)
.
也许您应该删除$('label .'+group)
.
$('label .'+group)
means all the elements with the group class in all <label>
, while $('label.'+group)
means the all <label>
with group class.
$('label .'+group)
表示在 all 中具有 group 类的所有元素<label>
,而$('label.'+group)
表示所有<label>
具有 group 类的元素。