This question already has answers here:
Event binding on dynamically created elements?
                            
                                (23个答案)
                            
                    
                4年前关闭。
        

    

我将数据动态附加到表中,如下所示:

function myFunctionEdit()
{

var table = document.getElementById("nomiTable");
var len = table.rows.length;
var row = table.insertRow(len);
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);

cell1.innerHTML = len;
cell2.innerHTML = name;
cell3.innerHTML = dob;
cell4.innerHTML = relation;
cell5.innerHTML = share;
cell6.innerHTML = "<a href = \"#\" data-toggle=\"modal\" data-target=\"#editNomiModal\" id = \"editNominHref\" name = \"editNominHref\" ><img border=\"0\" alt=\"Edit Nominee\" src=\"images/edit.png\" width=\"15\" height=\"15\"/></a>";

$('#editNomiModal').modal('hide');
return false;
}


我的表结构是:

<table id = "nomiTable" name = "nomiTable" class="table table-striped table-hover">
<thead>
<tr>
..
</tr>
</thead>
<tbody>
<tr>
..Dynamically generated columns...
<td>
<a href = "#" data-toggle="modal" data-target="#editNomiModal" id = "editNominHref" name = "editNominHref" >
<img border="0" alt="Edit Nominee" src="images/edit.png" width="15" height="15"/>
</a>
</td>
</tr>


#editNominHref上的jQuery函数单击:

$("#editNominHref").on('click', function(e)
{
alert($(this).closest('tr').index());
});


问题:
该方法不适用于动态生成的Edit Hrefs。任何帮助将不胜感激。

最佳答案

使用event delegation相同。

$(document).on('click', '#editNominHref', function(e)
{
    alert($(this).closest('tr').index());
});

09-10 12:02