2010-10-07 20 views
2

我試圖改變一個父容器內的所有複選框的ID的,但我迄今OT能得到它的工作,這是我的代碼中的多個輸入的ID的,改變使用jQuery

HTML:

<div data-custom='other_container' class='container'> 
<h3>Other:</h3> 
<div class='container'> 
    <label for='monitoring'>Monitoring and verification of energy savings: </label> 
    <div> 
    <input type='checkbox' name='other' id='monitoring' class='validate[minCheckbox[1]] checkbox' /> 
    </div> 
</div> 
<div class='container'> 
    <label for='engineering'>Engineering & project management: </label> 
    <div> 
    <input type='checkbox' name='other' id='engineering' class='validate[minCheckbox[1]] checkbox' /> 
    </div> 
</div> 
<div class='container'> 
    <label for='energy_audits'>Energy audits: </label> 
    <div> 
    <input type='checkbox' name='other' id='energy_audits' class='validate[minCheckbox[1]] checkbox' /> 
    </div> 
</div> 
</div> 

的jQuery:

$("[data-custom='other_container']").children('input').attr('id', 'test'); 

什麼可能是錯的這個任何想法?

Thanx提前。

回答

3

data-custom='other_container'元素沒有任何子元素<input>元素。

您應該use .find() instead

$("[data-custom='other_container']").find('input').attr('id', 'test'); 

.find()方法將通過所有後代搜索,whereas .children()只着眼於眼前的孩子。

但請記住,ID必須是唯一的,因此您需要確保爲每個ID分配唯一的ID。你可以做這樣的事情:

$("[data-custom='other_container']").find('input').attr('id', function(i) { 
     return 'test' + i; 
}); 

而且,這是一個好主意,給div標籤名稱在這種情況下選擇,所以jQuery是不是在看data-custom屬性每元素。

$("div[data-custom='other_container']") 

您還可以通過將.container類添加到選擇器中使其更加具體。

$("div.container[data-custom='other_container']") 
0

data-custom不必是<input>

您可以使用它代替任何兒童 -

$("[data-custom='other_container'] input").attr('id', 'test'); 

上面的代碼將搜索<input>在所有兒童,盛大,兒童等並替換他們的ID。你的代碼只在data-custom

你的代碼兒童使用的搜索等同於 -

​​
0

jQuery的children()只選擇所選元素的兒童;它不會抓住所有的後代(即兒童,他們的孩子等),這是你想要的。在你的榜樣......

$("[data-custom='other_container']").children() 

...只有抓住other_container的孩子,即你的H3和div.container元素。添加「輸入」過濾器根本不會選擇任何元素。

要查找特定類型的所有後代,請使用jQuery的find()。您的代碼可以改寫爲:

$("[data-custom='other_container']").find('input') 

最後,請記住所有元素ID都必須是唯一的。如果他們不是,嘗試類似$('#this-id-is-not-unique')會讓你大失所望。如果您需要對每個輸入應用相同的標識符,請考慮爲每個元素添加一個類。