2

我正在尝试更新一组 divclass="oct_days"以根据:nth-child(n). 的格式idoct_n. 我正在尝试使用 for 循环为 div 设置它来完成此操作。

window.onload = function addOctDate() {
    var cls = document.getElementByClass("oct_days");
    for (var n = 1; n < 32; n++) {
        cls[n].id = "oct_" + n;
    }
};

小提琴(http://jsfiddle.net/ascottz/D9Exm/

这个想法是.oct_days:nth-child(1)have id="oct_1",但没​​有设置 id 。

4

4 回答 4

3

cls你的问题是这样的:

  1. window.onload 在您的 html 初始化之前正在运行
  2. document.getElementsByClassName你不需要打电话
  3. 您从 1 开始迭代,索引基于 0,您应该从那里开始并添加+ 1如下所述
  4. 此外,在迭代时,最好只迭代列表中的已知项目

试试这个代码:

function addOctDate() {
        var cls = document.getElementsByClassName("oct_days"); 
        for (n=0, length = cls.length; n < length; n++) {
            cls[n].id= "oct_" + (n + 1); 
        }
    }; 

addOctDate()
于 2013-10-09T01:48:11.897 回答
2

功能是getElementsByClassName

小提琴不起作用,因为您看到window.onload代码已经在该事件中运行(左侧的下拉菜单显示 onLoad)。它也会出错,因为 HTML 中没有 31 个元素,但它仍会设置 ID。

于 2013-10-09T01:37:00.707 回答
1

您的代码很容易修复

(function () {

  // .getElementsByClassName not .getElementByClass
  var cls = document.getElementByClassName("oct_days"),
  // set the stopping point DYNAMICALLY
      len = cls.length,
  // start the index at 0;
      n = 0;
  for (; n < len; n++) {
    cls[n].id = "oct_" + (n + 1);
  }
// ()(); auto runs the function 
})();
于 2013-10-09T01:48:33.380 回答
0

这是一种仅使用纯 js 向元素和类添加 id 的方法。

HTML

<div id="test">
    Content will append below!
    <input type="button" value="click me!" onClick="myFunction();"/>
</div>

CSS

.cool_0 {
    background: red;
    height: 200px;
    width: 100%;
}
.cool_1 {
    background: yellow;
    height: 200px;
    width: 100%;
}
.cool_2 {
    background: red;
    height: 200px;
    width: 100%;
}
.cool_3 {
    background: yellow;
    height: 200px;
    width: 100%;
}
.cool_4 {
    background: red;
    height: 200px;
    width: 100%;
}
.cool_5 {
    background: yellow;
    height: 200px;
    width: 100%;
}

JS

function myFunction(){
        var myId = 0;
        var counter = 0;
        var myDiv = document.getElementById("test")
        for(var i = 0; i < 5; i++){
            var textNode = document.createTextNode("sup! My current id is "+myId+" !")
            var t = document.createElement("div");
            t.setAttribute("id", counter++)
            t.setAttribute("class", "cool_"+myId++)
            t.appendChild(textNode)
            myDiv.appendChild(t);
        }
    }
于 2017-11-19T22:52:48.183 回答