如何从具有相同id的div标签获取数据

时间:2016-06-29 08:53:52

标签: javascript jquery html

Html

    if(session == null && !(uri.endsWith("html") || uri.endsWith("LoginServlet")|| uri.endsWith("jsp"))){
        this.context.log("Unauthorized access request");
        res.sendRedirect("index.html");
    }else{
        // pass the request along the filter chain
        chain.doFilter(request, response);
    }


}
    @Override
public void destroy() {
    //close any resources here
}

}

我在div中有两个带有类名的div,通过函数我可以得到<!DOCTYPE html> <html> <body> <div id="one"> welcome <div class="two"> hello world </div> <div class="two"> bye world </div> </div> <button onclick="myFunction()"> Click</button> <p id="demo"></p> <script> function myFunction() { var x = document.getElementsByClassName('two')[0].innerHTML; document.getElementById('demo').innerHTML = x; } </script> </body> </html> i的数据。 hello world.here我想要所有数据一个接一个地使用相同的类名。我想用class="two"打印所有数据,即hello world,bye world.plz帮助我

3 个答案:

答案 0 :(得分:0)

  • 使用Array#map以数组
  • 的形式获取每个元素的所有文本
  • 使用Array#join将数组中的所有项目,连接为glue

注意:[].map用于在DOMCollection上使用map数组方法。

&#13;
&#13;
function myFunction() {
  var x = document.getElementsByClassName('two');
  var mapped = [].map.call(x, function(el) {
    return el.innerHTML; //Or el.textContent;
  });
  document.getElementById('demo').innerHTML = mapped.join(',');
}
&#13;
<div id="one">
  welcome
  <div class="two">
    hello world
  </div>
  <div class="two">
    bye world
  </div>
</div>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用jQuery&#39; each函数

我们可以通过使用jQuery的每个功能来实现这一点。首先,我们按下数组中的每个项目,然后用逗号分隔打印它。

我们使用push函数推送数组中的每个项目,然后使用join来显示它。

<script>
  function myFunction(){
     msg = array();
     $('.className').each(function(){
        msg.push($(this).html());
     });

     $('#demo').html(msg.join(", "));
  }
</script>

答案 2 :(得分:0)

类名将获得一个节点列表,因此需要循环。将所有innerhtml存储在一个变量中,然后添加到您的元素中。

 function myFunction() {
            var x = document.getElementsByClassName('two');
            var t="";
            for(var i = 0;i < x.length;i++){
              t += (i == x.length -1) ? x[i].innerHTML : x[i].innerHTML+",";
           }
           document.getElementById('demo').innerHTML = t;
        }