如何在javascript中动态创建事件和事件处理程序

时间:2013-08-26 16:04:32

标签: javascript html events dynamic handler

我正在尝试使用for循环动态创建具有唯一侦听器和处理程序的按钮,但不幸的是我必须做错了,因为只有最后一个按钮才能工作。 更令人惊讶的是,当点击最后一个按钮而不是“按钮No.3”时,它返回“按钮No.4”

Bellow是代码,这里是jsfiddle http://jsfiddle.net/y69JC/4/

HTML:

<body>
    <div id="ui">
    some text ...
    </div>
</body>

使用Javascript:

var uiDiv = document.getElementById('ui');
uiDiv.innerHTML = uiDiv.innerHTML + '<br>';

var results = ["Button one","Button two","Button three","Button four"];

for(var n=0;n<results.length;n++)
{
 uiDiv.innerHTML = uiDiv.innerHTML + '<button id="connect'+n+'">option'+n+':'+results[n]+'</button><br>';
 var tempId = document.getElementById('connect'+n);
 tempId.addEventListener('click', function(){console.log("Button No."+n)}, false);
}

谢谢!

3 个答案:

答案 0 :(得分:2)

当您需要闭包时,这是一个经典案例:转到:

var uiDiv = document.getElementById('ui');
uiDiv.innerHTML = uiDiv.innerHTML + '<br>';

var results = ["Button one", "Button two", "Button three", "Button four"];

for (var n = 0; n < results.length; n++) {
    // Note: do not use .innerHTML. Create new element programatically
    //       and then use .appendChild() to add it to the parent.
    var button = document.createElement('button');
    button.id = 'connect' + n;
    button.textContent = 'option' + n + ':' + results[n];

    uiDiv.appendChild(button);

    button.addEventListener('click', /* this is an inline function */ (function (n2) {
        // Here we'll use n2, which is equal to the current n value.
        // Value of n2 will not change for this block, because functions
        // in JS do create new scope.

        // Return the actual 'click' handler.
        return function () {
            console.log("Button No." + n2)
        };
    })(n)); // Invoke it immediately with the current n value
}

原因是for循环不会创建范围,因此"Button No. " + n的评估总是n等于results中的元素数量阵列。

必须要做的是创建一个内联函数,接受n作为参数,并使用当前值n将其称为立即。然后,此函数将返回click事件的实际处理程序。请参阅this答案,了解一个简单明了的例子。

编辑:您的代码正在使用innerHTML属性在循环中添加新按钮。它被破坏是因为每次使用uiDiv.innerHTML = ...分配时,您将删除此div中先前存在的所有内容并从头开始重新创建它们。这导致了以前附加的所有事件处理程序的删除。原理上,它看起来像这样:

uiDiv.innerHTML = ""

// First iteration of for-loop
uiDiv.innerHTML === <button1 onclick="...">

// Second iteration of for-loop
// 'onclick' handler from button1 disappeared
uiDiv.innerHTML === <button1> <button2 onclick="...">

// Third iteration of for-loop
// 'onclick' handler from button2 disappeared
uiDiv.innerHTML === <button1> <button2> <button3 onclick="...">

答案 1 :(得分:0)

事件处理程序绑定到n,事件触发时的值为results.length

您必须通过复制来关闭 n的值,您可以通过调用函数来执行此操作。这种结构称为闭包

for(var n=0;n<results.length;n++)
{
 uiDiv.innerHTML = uiDiv.innerHTML + '<button     id="connect'+n+'">option'+n+':'+results[n]+'</button><br>';
 var tempId = document.getElementById('connect'+n);
 tempId.addEventListener('click', (function(bound_n) {
   console.log("Button No."+ bound_n);
 })(n)), false); // <-- immediate invocation
}

如果n是一个对象,这将无效,因为对象(与标量不同)通过引用传递。

避免在所有for循环中编写闭包的一个好方法是不使用for循环而是使用带回调的map函数。在这种情况下,您的回调就是关闭,因此您可以免费获得预期的行为:

function array_map(array, func) {
    var target = [], index, clone, len;
    clone = array.concat([]); // avoid issues with delete while iterate
    len = clone.length;
    for (index = 0; index < len; index += 1) {
        target.push(func(clone[index], index));
    }
    return target;
}

array_map(results, function (value, n) {
    uiDiv.innerHTML = uiDiv.innerHTML
      + '<button id="connect'+n+'">option'+n+':'+results[n]+'</button><br>';
    var tempId = document.getElementById('connect'+n);
    tempId.addEventListener('click', function(){console.log("Button No."+n)}, false);    
});

答案 2 :(得分:0)

你可以写

onclick = 'myFunction(this.id):'
然后在按钮中

function myFunction(idNum){console.log("Button No."+idNum);}

此处还有一些您可能想要实施的改进:

uiDiv.innerHTML = uiDiv.innerHTML + ....;
uiDiv.innerHTML += ....;

你也想在循环之前声明“uiDivContent”,然后再写:

uiDiv.innerHTML = uiDivContent;
相关问题