从容器div中的childNode获取值

时间:2017-04-14 05:38:36

标签: javascript jquery

$(document).ready(function(e){
  var newNode = $('#origin').clone();
  $('#container').append(newNode);
  for(var i=0; i<$('#container').children().length; i++)
   $('#result').append($('#container').children(i).html()+"<br>");
});
<html>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<body>
<span id='origin' my-data='somedata'>Hello</span>
<div id='container'>
  <span emoji-data='mmm'>a</span>
  <span>b</span>
  <span>
    <span>b1</span>
    <span>b2</span>
  </span>
  <span>c</span>
</div>
<p></p>
<b>Content inside every nodes:</b>
<div id='result'></div>
</body>
</html>

预期结果是:a,b,.... 但在这方面,我只得到了一个价值。怎么解决?谢谢!

1 个答案:

答案 0 :(得分:2)

如果您想将搜索限制为仅限某些元素,则不会将数字传递给children函数,而是传递选择器。例如,如果您只想要<span>个元素,则可以使用$("#container").children("span")

您希望在子项上使用each function,而不是使用for循环,并使用回调函数附加其内容:

&#13;
&#13;
$(document).ready(function(e){
  var newNode = $('#origin').clone();
  $('#container').append(newNode);
  $('#container').children().each(function(el) {
    $('#result').append($(this).html()+"<br>");
  });
});
&#13;
<html>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<body>
<span id='origin' my-data='somedata'>Hello</span>
<div id='container'>
  <span emoji-data='mmm'>a</span>
  <span>b</span>
  <span>
    <span>b1</span>
    <span>b2</span>
  </span>
  <span>c</span>
</div>
<p></p>
<b>Content inside every nodes:</b>
<div id='result'></div>
</body>
</html>
&#13;
&#13;
&#13;