如何在Jquery中动态添加onclick?

时间:2015-02-11 10:50:44

标签: jquery

我有以下代码:

 obj2 = JSON.parse(ajax.responseText);
        for (var i = 0; i <= obj2.length - 1; i++) {

            var row = table.insertRow(1);
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            var cell4 = row.insertCell(3);
            var cell5 = row.insertCell(4);
            var cell6 = row.insertCell(5);
            var cell7 = row.insertCell(6);
            var cell8 = row.insertCell(7);

            cell1.innerHTML = obj2[i].qid;
            cell2.innerHTML = obj2[i].question;
            cell3.innerHTML = obj2[i].answer1;
            cell4.innerHTML = obj2[i].answer2;
            cell5.innerHTML = obj2[i].answer3;
            cell6.innerHTML = obj2[i].answer4;
           $(function(){
                var btn = document.createElement("BUTTON");        
                var t = document.createTextNode("Delete "+cell1.innerHTML); //this works well     
                btn.appendChild(t);   
                btn.className="menu_buttons";
                $(btn).on('click' ,function(){
                    delete_(cell1.innerHTML);//this assigns the value of the last iteration to each button


                });
                cell8.appendChild(btn);
            });
            }

我正在迭代一个json数组,我想将相同的函数(具有不同的参数,取决于数组中的id)分配给每个按钮,正如我在评论中提到的,它会覆盖每个按钮。相同的参数。 怎么了?

1 个答案:

答案 0 :(得分:0)

创建动态按钮,并附加这样的事件处理程序

HTML

<div id="test"></div>

JS

for(i = 1; i <=10; i++) {
     var test = $('<button/>',
    {
        text: 'D.Button',
        click: function () { alert('test'); }
    });
     $('#test').append(test);
  }

<强> DEMO