简体   繁体   English

如何仅使用javascript获取框索引号

[英]How to get box index number using only javascript

i want to get box index number using Javascript. 我想使用Javascript获取框索引号。 like i have four box so i want each box text have this appropriate number. 就像我有四个盒子所以我希望每个盒子文本都有这个合适的数字。

<head>

  <script type="text/javascript">
  function () {
   var Main= document.getElementById('container').getElementsByTagName('div');

for(i=0; i<Main.length;i++){



}

  }
  </script>
  <style>
  .box {
    float:left;
    margin-left:20px;
    position:relative
  }
  .width {
    position:absolute;
    left:0;
    top:0;
    color:#FFF;
    font-size:20px;
  }
  </style>
</head>
<body>
  <div id="container">
    <div class="box">

      <img src="img/sample1.jpg" height="200" width="300" />
    </div>
    <div class="box">

      <img src="img/sample2.jpg" height="200" width="350" />
    </div>
    <div class="box">

      <img src="img/sample3.jpg" height="200" width="150" />
    </div>
    <div class="box">

      <img src="img/sample4.jpg" height="200" width="100" />
    </div>
  </div>
</body>
window.onload=function() {
   var Main= document.getElementById('container').getElementsByTagName('div');

  for(var i=0; i<Main.length;i++){
    Main[i].innerHTML+= '<span class="title">box '+(i+1)+'</span>';
  }
}

DEMO DEMO

Replace all your JS with this below and place the script tag as the last tag in your body tag to assure the DOM is ready when this is called. 用下面的替换所有JS,并将脚本标记作为body标记中的最后一个标记,以确保在调用DOM时DOM已准备就绪。 You could also call this function from the onload event. 您也可以从onload事件中调用此函数。

(function(){
    var Main= document.getElementById('container').getElementsByTagName('div');
    for(var i=0; i<Main.length;i++){
      Main[i].innerHTML += "box"+i;
    }
})();

http://jsfiddle.net/mmjW9/ http://jsfiddle.net/mmjW9/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM