可能重复:
Javascript 仅设置数组中最后一项的属性
我刚刚深入学习了一些基本的 javascript+dom 学习,但不能完全理解只有最后一个元素被切换?我对为什么将事件附加到元素感到迷茫,似乎也覆盖了以前的事件。
JavaScript:
window.onload = function() {
// Simple log
var c = function(x) {
return console.log(x);
};
var hasClass = function(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
var toggleClass = function(ele, cls) {
if (!hasClass(ele, cls)) {
ele.className += " " + cls;
} else {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, '');
}
};
var toggle = function(clk) {
c(clk);
}
var el = document.getElementsByClassName('time');
for (i = 0; i < el.length; i++) {
var btnToggle = el[i].getElementsByClassName('btn-toggle')[0];
var clk = el[i].getElementsByClassName('clock')[0];
btnToggle.addEventListener('click', function() {
toggle(clk)
}, false);
}
};
HTML:
<section>
<div class="time">
<a href="#" class="btn-toggle">Show the time</a>
<div class="clock">Clock1</div>
</div>
<div class="time">
<a href="#" class="btn-toggle">Show the time</a>
<div class="clock">Clock2</div>
</div>
<div class="time">
<a href="#" class="btn-toggle">Show the time</a>
<div class="clock">Clock3</div>
</div>
</section>
感谢您的明智建议!