0

重複の可能性:
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>
4

1 に答える 1

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>

したがって、一石二鳥です。a) マークアップは意味的にはるかに優れており、b)メソッドlabelを介して要素のコンテンツにアクセスできます.text()

最初の亜種はここで見ることができます: http://jsfiddle.net/skip405/DjWcg/

于 2012-04-22T18:53:30.393 に答える