是否可以将变量添加到jquery select函数中

时间:2014-02-22 20:25:41

标签: javascript jquery html css

您好我想选择一个与我的$ id变量同名的Class。

如果我自己添加div id但是我希望它基于我的$ id变量,一切正常。

这是可能的,还是有更好的方法根据点击的按钮定位正确的div?

$('.checkbox-group').find('input[value=button]').click(function() { //find all buttons with value=button

var $toggle = $(this); 
//add buttons in variable $toggle

var $id = $( this ).attr('id');                                     
//add the clicked button´s ID in the variable $id

if ($toggle.prop('checked') === true) {                             
//if the clicked button is checked 

$('#my-grp div.$id').removeClass('kill');                       
//want to select the div with Class that have same name as my $id variable

} else {
//and then add or remove the class .kill

$('#my-grp div.$id').addClass('kill');                          
}
});

3 个答案:

答案 0 :(得分:1)

解决方案只是一个简单的字符串连接:)

$('#my-grp div.' + $id).removeClass('kill');

答案 1 :(得分:0)

jQuery不会在字符串引号中处理变量,你应该连接它。

而不是:

$('#my-grp div.$id').removeClass('kill');

写下这个:

$('#my-grp div.' + $id).removeClass('kill');

编辑:糟糕,它看起来有人更快:)

答案 2 :(得分:0)

您可以连接字符串和变量。在你的情况下像这样:

$('#my-grp div.' + $id ).removeClass('kill');

旁注: javascript中的变量不需要$。在你的情况下,id将是一个更好的变量名来存储字符串。

$通常用于存储jquery元素,例如$toggle

相关问题