2012-04-22 55 views
0

可能重複:
How do I select text nodes with jQuery?訪問文本節點旁邊的複選框,JQuery的

我試圖移動是在文本節點上相鄰的選擇複選框中的數據複選框。我正在使用jQuery。下面列出了我嘗試過的方法和我收到的結果。

<input class="item" type="checkbox" /> Category 1 
<input class="item" type="checkbox" /> Category 2 


<script> 
    $('.item').click(function(){ 
     if($(this).attr('checked')) 
     { 
     $('#list').append("<span>" + $(this).next() + "<span><br/>") 
     //$(this).next() just writes "[object Object]" 
     //$(this).next().text() doesn't write anything 
     //Also tried $(this).nextSibling.nodeValue but throws "Cannot access property of undefined" 
     } 
     else 
     { 
      //This is remove the item from the list on uncheck 
     } 
    }); 
</script> 
+0

可能會更容易。但'[object Object]'意味着你得到的是DOM元素,而不是它的內容。你試過'$(this).next()。val()'? – Marc 2012-04-22 18:37:37

+0

這個問題與之前關於這個主題的問題完全一樣。其答案可能會與另一個相同的問題合併。 http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery – iambriansreed 2012-04-22 18:37:38

+0

$(this).next()。val()在我的列表中寫入「undefined」。我真的不想使用其他示例,因爲我實際上只是試圖訪問下一個節點。我會嘗試把它放在小提琴中,但複選框項目列表正在由另一個js文件生成。我試圖貶低它以專注於這個實際問題。 – ExceptionLimeCat 2012-04-22 19:04:30

回答

0

考慮有這個標記,而不是

<input class="item" type="checkbox" id="cat_one" name="cat_one" /> <label for="cat_one">Category 1</label> 
<input class="item" type="checkbox" id="cat_two" name="cat_two"/> <label for="cat_two">Category 2</label> 

或本:

<label for="cat_one"><input class="item" type="checkbox" id="cat_one" name="cat_one" /> Category 1</label> 
<label for="cat_two"><input class="item" type="checkbox" id="cat_two" name="cat_two"/> Category 2</label> 

因此,你一舉兩得:一)您的標記是遠遠語義更好,b)您可以通過.text()方法訪問label元素內容。

第一個變種可以在這裏看到:如果你把這個小提琴,所以我們可以看到你所使用的元素http://jsfiddle.net/skip405/DjWcg/

+0

事實上,我通過將事件設置爲節點樹中更高級別的錨點並訪問它的文本節點來實現它。但我認爲如果我沒有走這條路,這種方法就行得通。謝謝。 – ExceptionLimeCat 2012-04-23 20:10:32

相關問題