开发者

What would stop a jQuery function from firing after replacing HTML on the page with similar elements?

开发者 https://www.devze.com 2023-01-23 22:39 出处:网络
If I have the following HTML: <tr id=\"record_1\" > <td id=\"name_1\"><a href=\"#\" class=\"logNameAndValue\">Charles Dickens</a></td><td id=\"value_1\">A Christma

If I have the following HTML:

<tr id="record_1" >
<td id="name_1"><a href="#" class="logNameAndValue">Charles Dickens</a></td><td id="value_1">A Christmas Carol</td>
</tr>

And another jQuery function is called to replace it with this:

<tr id="record_1" >
<td id="name_1"><a href="#" class="logNameAndValue">Kurt Vonnegut</a></td><td id="value_1">Slaughterhouse Five</td>
</tr>

After the replacement, the onClick function no longer works:

$('a.logNameAndValue').click( function(event){
    console.log("clicked!");
});

I tried moving all jQuery functions from being defined inside the <body> tag to the <head> tag but it made 开发者_高级运维no difference.

I've monitored activity in the Firebug Console and Net panels and Firebug doesn't indicate a click has taken place.

But the .click works fine when the page is first loaded.

Any suggestions?


You need to use live():

$('a.logNameAndValue').live('click',function(event){
    console.log("clicked!");
});

Since element is generated dynamically, the normal click hanlder won't work and that's where live() comes in.

Description: Attach a handler to the event for all elements which match the current selector, now and in the future.


That click handler is attached to that particular element in the DOM. When you remove the original element, you remove the handler. If you use .delegate() or .live() instead, you won't have this problem.


you need to use .live instead of .click

$('a.logNameAndValue').live('click', function(event){
    console.log("clicked!");
});
0

精彩评论

暂无评论...
验证码 换一张
取 消