我已经看到了这个主题的问题,但没有任何效果。我试图在点击时将一个按钮(总共九个按钮)添加到“push-2”。
我正在使用'for'循环,但是我得到了这个版本的Messgae:
未捕获的TypeError:无法读取属性'className'的null(...)
但当我做 console.log(document.querySelector(givenselector [i])。className);
它正确打印类
这是我的HTML:
<div id="gameboard">
<ul class="clearfix">
<li><button class="gameboard-button unpushed" id="btn1">+</button></li>
<li><button class="gameboard-button unpushed" id="btn2">+</button></li>
<li><button class="gameboard-button unpushed" id="btn3">+</button></li>
<li><button class="gameboard-button unpushed" id="btn4">+</button></li>
<li><button class="gameboard-button unpushed" id="btn5">+</button></li>
<li><button class="gameboard-button unpushed" id="btn6">+</button></li>
<li><button class="gameboard-button unpushed" id="btn7">+</button></li>
<li><button class="gameboard-button unpushed" id="btn8">+</button></li>
<li><button class="gameboard-button unpushed" id="btn9">+</button></li>
</ul>
</div>
AndHere是我的javaScript
document.addEventListener("DOMContentLoaded", function(event) {
(function (global){
var givenselector = new Array();
for (i=0; i<9; i++){
j=i+1;
givenselector[i] = "#btn"+j;
document.querySelector(givenselector[i]).addEventListener("click",function (event){
var classes = document.querySelector('givenselector[i]').className;
classes += " pushed-2";
document.querySelector(givenselector[i]).className = classes;
document.querySelector(givenselector[i]).innerText = "x";
});
}
})(window);
});
答案 0 :(得分:0)
不要在for循环中使用函数,并使用选择器[id^='btn']
开始选择所需的元素。
var btns = document.querySelectorAll("[id^='btn']");
for(i=0; i<btns.length; i++){
btns[i].className += " pushed-2";
btns[i].innerHTML = "x";
};
console.log(btns);
&#13;
<div id="gameboard">
<ul class="clearfix">
<li><button class="gameboard-button unpushed" id="btn1">+</button></li>
<li><button class="gameboard-button unpushed" id="btn2">+</button></li>
<li><button class="gameboard-button unpushed" id="btn3">+</button></li>
<li><button class="gameboard-button unpushed" id="btn4">+</button></li>
<li><button class="gameboard-button unpushed" id="btn5">+</button></li>
<li><button class="gameboard-button unpushed" id="btn6">+</button></li>
<li><button class="gameboard-button unpushed" id="btn7">+</button></li>
<li><button class="gameboard-button unpushed" id="btn8">+</button></li>
<li><button class="gameboard-button unpushed" id="btn9">+</button></li>
</ul>
</div>
&#13;