动态绑定onclick事件为for循环中的所有按钮提供相同的值

时间:2022-10-22 07:57:32

I am trying to create buttons dynamically and assining an alert function for each one on a click event.Here is the javascript function as:

我正在尝试动态创建按钮并在点击事件中为每个按钮提供警报功能。这里的javascript函数如下:

function GetTabs(tabObj) {
   for (var t = 0; t < tabObj.views.view.length; t++) {               
        var podObjlen = '';
        var element = document.createElement('input');
        element.id = "btn" + t;
        element.setAttribute("type", "button");
        element.setAttribute("value", "Click");
        element.setAttribute("name", "button");
        podObjlen = tabObj.views.view[t].pod.length;
        document.body.appendChild(element);
        document.getElementById('btn' + t).onclick = (this, "onclick", function {
           alert(podObjlen);                    
        });                
    }
}

No matter what button i click the alert always shows me the last value from the loop for all the buttons i.e length value is being assigned to all the alerts. It isn't assigning independent values for each alert of a button. I have tried several ways like:

无论我点击什么按钮,警报总是向我显示所有按钮的循环中的最后一个值,即长度值被分配给所有警报。它没有为按钮的每个警报分配独立值。我尝试过几种方式:

element.getElementById('btn' + t).onclick = (this, "onclick", function {
    alert(podObjlen);                    
}); 
element.getElementById('btn' + t).onclick = new function () {
    alert(podObjlen);
}

(Here it shows me proper values in alertbox but i get alert one after the other continously but the alert fails to fire when i actually click a button i.e the alert fires the moment my buttons are rendered. Hope i am being clear. What i want is i need to get the actual value to be assingned to alert of each button when the loop is being run.

(这里它显示了我在警告框中的正确值,但我一个接一个地得到警报,但当我实际点击一个按钮时警报无法触发,即警报触发我的按钮被渲染的那一刻。希望我很清楚。我想要什么是否需要在运行循环时获取实际值以确定每个按钮的警报。

1 个解决方案

#1


5  

Adnan what you are observing is infamous loop problem in javascript. Which occurs due to less understanding around how javascript works it has also been discussed in a previous post here

您正在观察的Adnan是javascript中臭名昭着的循环问题。由于对javascript如何工作的理解较少而发生这种情况,这也在此前的帖子中进行了讨论

Javascript infamous Loop issue?

Javascript臭名昭着的循环问题?

#1


5  

Adnan what you are observing is infamous loop problem in javascript. Which occurs due to less understanding around how javascript works it has also been discussed in a previous post here

您正在观察的Adnan是javascript中臭名昭着的循环问题。由于对javascript如何工作的理解较少而发生这种情况,这也在此前的帖子中进行了讨论

Javascript infamous Loop issue?

Javascript臭名昭着的循环问题?