用于循环和传递值的addEventListener我试图使用for循环将事件侦听器添加到多个对象,但最终导致所有侦听器以同一个对象->最后一个对象为目标。如果我通过为每个实例定义Boxa和boxB来手动添加侦听器,它就能工作。我想是加载项事件循环没有按我所希望的方式工作。也许我使用了错误的方法。示例在容器4上使用4类=“容器”触发器的工作方式。在容器4上的容器1,2,3触发器事件上触发,但仅当触发器已被激活时。// Function to run on click:function makeItHappen(elem, elem2) {
var el = document.getElementById(elem);
el.style.backgroundColor = "red";
var el2 = document.getElementById(elem2);
el2.style.backgroundColor = "blue";}// Autoloading function to add the listeners:var elem = document.getElementsByClassName("triggerClass");for (var i = 0; i < elem.length; i += 2) {
var k = i + 1;
var boxa = elem[i].parentNode.id;
var boxb = elem[k].parentNode.id;
elem[i].addEventListener("click", function() {
makeItHappen(boxa, boxb);
}, false);
elem[k].addEventListener("click", function() {
makeItHappen(boxb, boxa);
}, false);}<div class="container">
<div class="one" id="box1">
<p class="triggerClass">some text</p>
</div>
<div class="two" id="box2">
<p class="triggerClass">some text</p>
</div></div><div class="container">
<div class="one" id="box3">
<p class="triggerClass">some text</p>
</div>
<div class="two" id="box4">
<p class="triggerClass">some text</p>
</div></div>
3 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
function(){makeItHappen(boxa,boxb);}
博萨
function makeItHappenDelegate(a, b) { return function(){ makeItHappen(a, b) }}// ... elem[i].addEventListener("click", makeItHappenDelegate(boxa,boxb), false);
添加回答
举报
0/150
提交
取消