2

テーブルのデータに 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テンプレートに切り替えるまで、以前は機能していました。助言がありますか?ありがとう!

4

1 に答える 1

2

準備ができた<tr id= "#indexTR">ときに DOM に存在しないため、デリゲート イベントを使用するとうまくいくはずです。

$('#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。あなたの質問のコメントで議論されているように。

于 2012-05-02T00:31:29.250 に答える