使用用JavaScript创建的按钮来调用函数

时间:2014-03-22 12:19:32

标签: javascript

我从在线服务中检索事件列表,以显示结果我动态创建包含信息和按钮的HTML div。

for(var i = 0; i < EventsArray.length; i++)
    {
        console.log(EventsArray[i]);

        var EventLine = document.createElement("div");
        EventLine.style.display="inline";

        var element = document.createElement("p");

        var Event = document.createTextNode(EventsArray[i][0]+' '+EventsArray[i][2]);
        element.appendChild(Event);

        var button = document.createElement("input");
        //Assign different attributes to the element. 
        button.type = "button";
        button.value = "Re-Invite Users"; 
        button.name = "Re-Invite";              

        button.onclick = 
        function(EventsArray) {
            var nonReplying = new Array(getNoreply(EventsArray[i][1])); 
            //unInviteUsers(EventsArray[i][1], nonReplying);
        };          

        EventLine.appendChild(element);
        EventLine.appendChild(button);
        eventsList = document.getElementById("Events");
        eventsList.appendChild(EventLine);

    } 

除按钮外,一切正常:

button.onclick = 
        function(EventsArray) {
            var nonReplying = new Array(getNoreply(EventsArray[i][1])); 
            //unInviteUsers(EventsArray[i][1], nonReplying);
        };   

运行时会发生错误:

  

TypeError:&#39; undefined&#39;不是一个对象(评估&#39; EventsArray [i] [1]&#39;)

由于当网页加载时,EventsArray不存在我无法设置button.onlick up ...

有关如何解决此问题的任何建议吗?

2 个答案:

答案 0 :(得分:0)

也许只是删除参数?

button.onclick = 
    function() {
        var nonReplying = new Array(getNoreply(EventsArray[i][1])); 
        //unInviteUsers(EventsArray[i][1], nonReplying);
    };   

答案 1 :(得分:0)

您可以将函数包装在闭包中以获取循环内项的值,或使用bind创建具有默认参数的新函数。

测试jsfiddle:http://jsfiddle.net/BwVNC/

function getNoreply(item) {
    return "noreply" + item;
}

var EventsArray = [
    ['first0', 0, 'third0'],
    ['first1', 1, 'third1'],
    ['first2', 2, 'third2'],
    ['first3', 3, 'third3'],
]

for(var i = 0; i < EventsArray.length; i++)
    {
        console.log(EventsArray[i]);

        var EventLine = document.createElement("div");
        EventLine.style.display="inline";

        var element = document.createElement("p");

        var Event = document.createTextNode(EventsArray[i][0]+' '+EventsArray[i][2]);
        element.appendChild(Event);

        var button = document.createElement("input");
        //Assign different attributes to the element. 
        button.type = "button";
        button.value = "Re-Invite Users"; 
        button.name = "Re-Invite";              

        button.onclick = function(item) {
            var nonReplying = new Array(getNoreply(item)); 
            console.log(nonReplying);
        }.bind(button, EventsArray[i][1]);

        EventLine.appendChild(element);
        EventLine.appendChild(button);
        eventsList = document.getElementById("Events");
        eventsList.appendChild(EventLine);

    }