1

我有一个原始的 HTML,比如:

<tr>
  <td class = 'greatTD' id = 'great1'>I am too great to be anything less.</td>
</tr>

然后我通过 JavaScript 添加了一个元素,如下所示:

function AddStuff()
{
    var s = '<tr><td class = "greatTD" id = "great2">I am even greater.</td></tr>';

    $('#foo').after(s);
}

function WireHandlers()
{
    $('.greatTD').click(GreatTDClickHandler);
}

function GreatTDClickHandler()
{
    // not being called for #great2
    // how do I make it be called?
}

$(document).ready(function() { WireHandlers(); });
4

2 回答 2

3

The event handler is being assigned on load, before the .greatTD elements exist. Therefore you need to use a delegate handler, like this:

function WireHandlers() {
    $('#foo').on('click', '.greatTD', GreatTDClickHandler);
}

This attaches the event to the #foo element, which is present on load, and then filters it so that it's only executed on click of the .greatTD element.

于 2013-10-09T13:26:14.053 回答
1

以下应该工作。

$(document).on( 'click', '.greatTD', GreatTDClickHandler );

jQuery.on

于 2013-10-09T13:28:10.477 回答