jQuery - 逐个显示div

时间:2017-03-22 18:20:08

标签: javascript jquery html each

我正在尝试编写一个简单的脚本,它能够逐个读取/显示每个DIV(不会干扰其他内部的div)。不幸的是,我的想法并没有像我想象的那样奏效。我用.children().remove().each实现了我的目标,但发现它跳过了第一个div并删除了所有其他内部。如果有人可以帮助我或指出我做错了什么,我将非常感激。

$(function Testing(){
  
    $("div").each(function(){
        var Div = $(this).text();
        alert(Div);
    });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
    <div id="Alpha">
        Alpha
        <div id="Bravo">
            Bravo
            <div id="Charlie">
                Charlie
                <div id="Delta">
                    Delta
                </div>
            </div>
        </div>
    </div>
</body>

2 个答案:

答案 0 :(得分:2)

要获得所需的输出,您需要更改HTML,以便每个div仅包含您希望输出的文本。

运行此代码段时,您会注意到两个空白警报。这是因为SO(隐藏)在代码片段中放置了额外的div。这些额外警报不会显示在您的本地脚本中。

&#13;
&#13;
$(function Testing() {

  $("div").each(function() {
    var div_text = $(this).text();
    alert(div_text);
  });

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="Alpha">Alpha</div>
  <div id="Bravo">Bravo</div>
  <div id="Charlie">Charlie</div>
  <div id="Delta">Delta</div>
</body>
&#13;
&#13;
&#13;

此外,使用描述性变量。现在最好开始这种练习(因为你正在学习),这样你就不会养成坏习惯。我将Div更改为div_text作为示例。

答案 1 :(得分:2)

It looks like you want to have the nested structure. If that is the case you can do it at least a couple of ways:

$(function Testing() {

  $("#container div").each(function() {

    // my variation on this answer: http://stackoverflow.com/a/32170000/1544886
    var Div = $(this).contents().not($(this).children()).text();

    /* or another way: http://stackoverflow.com/a/33592275/1544886
      var Div = $(this)
        .clone()    //clone the element
        .children() //select all the children
        .remove()   //remove all the children
        .end()  //again go back to selected element
        .text(); 
    */

    alert(Div);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  <div id="Alpha">
    Alpha
    <div id="Bravo">
      Bravo
      <div id="Charlie">
        Charlie
        <div id="Delta">
          Delta
        </div>
      </div>
    </div>
  </div>
</div>

I added div#container ONLY because I didn't like the extra alerts generated from the divs created by having a code snippet. It's not necessary to do this in your code... you can ignore it and just use your selector $("div").