2014-02-22 37 views
0

您好我想選擇一個類與我的$ id變量具有相同名稱的div。是否有可能將一個變量添加到jQuery的選擇函數

一切工作,如果我自己添加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');       
} 
}); 
+1

包含一些示例HTML,以便我們可以看到您的代碼正在嘗試執行哪些操作。 – Keith

+0

這是JavaScript而不是PHP。在你的var之前你不需要'$',它不會在字符串中看到你的變量。你需要連接,就像在答案中一樣。 – Bill

回答

1

該解決方案僅僅是一個簡單的字符串連接遠:)

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

謝謝你的快速和簡單的答案:D – user3341623

0

jQuery將不會在字符串引號處理的變量,你應該串連它。

取而代之的是:

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

這樣寫:

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

編輯:糟糕,有人在快:)

0

可以Concat的字符串和變量。你的情況是這樣的:

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

旁註: 變量在JavaScript中不需要$。在你的情況下,id將是一個更好的變量名稱來存儲一個字符串。

$通常用於存儲jQuery元素,如$toggle

相關問題