JQuery 无法识别单击表行

本文关键字:单击 识别 JQuery | 更新日期: 2023-09-27 18:32:47

我正在使用 JQuery 模板来获取我的表的数据...CSS 识别查询模板脚本中的表行并按照我想要的方式设置它们的样式......但由于某种原因,我不能调用 $().单击使用相同的标识符的相同行。下面是表代码:

<script id="donorTemplate" type="text/x-jquery-tmpl">
<tr id="indexTR">
    <td>${Person.LastName}, ${Person.FirstName}</td>
    <td>${Address.Address1}</td>
    <td>${PhoneContact.PhoneNumber}</td>
    <td>${EmailContact.EmailContactx}</td>
    <td>${Company.CompanyName}</td>
    <td><a href="/Donation/Index?id=${Person.PersonID}">Add Donation</a></td>
    <td> <a href="/Person/Edit?id=${Person.PersonID}">Edit</a> &nbsp; <a href="/Person/Delete?    
id=${Person.PersonID}">Delete</a> &nbsp;
        <input type="hidden" id="hiddenField" value="${Person.PersonID}"/>
    </td> 
</tr>
</script>
<div id="searchresults">
<table id="donor-list">
<thead>
<tr>
    <th id="f" width="150">Name: </th>
    <th width="180">Address: </th>
    <th width="85">Phone: </th>
    <th width="150">Email: </th>
    <th width="100">Company: </th>
    <th width="100"></th>
    <th id="l" width="100"></th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>

还有JQuery...

$("#donorSearch").submit(function (event) {
        event.preventDefault();
        var form = $(this);
        $.getJSON(form.attr("action"), form.serialize(), function (data) {
            $("#tableBody #indexTR").remove();
            $("#donorTemplate").tmpl(data).appendTo("#tableBody");
        });
    });

那都是花花公子...但这不起作用:

$("#indexTR").click(function () {
       alert('test');
    });

这是我在TR点击时尝试做的事情:

var val = $("#hiddenField").val();
var personID = parseInt(val);
location.href = "/Person/Details?id=" + personID;

在我切换到 JQuery 模板之前一直有效。有什么建议吗?谢谢!

JQuery 无法识别单击表行

当 DOM 准备就绪时,<tr id= "#indexTR"> 中不存在,因此使用委托事件应该可以解决问题:

$('#donor-list').on('click', '#indexTR', function(){
    alert('test');
});

对于 jQuery 1.5:

$('#donor-list').delegate('#indexTR', 'click', function(){
    alert('test');
});

或者在每个新创建的行上附加回调。

$.getJSON(form.attr("action"), form.serialize(), function (data) {
        $("#tableBody #indexTR").remove();
        $("#donorTemplate").tmpl(data).appendTo("#tableBody");
        // Now attach the event:
        $("#indexTR").click(function () {
           alert('test');
        });
    });

并且您遇到了具有相同id的多个元素的问题. 如您的问题评论中所述。