2012-04-22 71 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