문제

As an example:

$('.edit_button').click(function() {
alert('test');
});

Now my HTML:

<div id='area1'><div class='edit_button'></div></div>
<div id='area2'><div class='edit_button'></div></div>
<div id='area3'><div class='edit_button'></div></div>

The area divs are inside a sortable div and I dynamically add and subtract or move the areas as needed, but when I do, the click functionality breaks. I believe it's because jquery click handlers only work on content that exists in the DOM when the function call is made.

My first solution was to reapply the relevant jquery every time an element was moved or removed, but I realized that the click events are stacking and now every time I click one of the buttons, the alert fires multiple times.

I thought that the reapplying click would just overwrite the existing click handler and all would be fine, but I'm writing more and more complex code to handle this situation which can't possibly be right. I must be doing something fundamentally wrong, but my brain is fried trying to work it all out.

What is the correct way to apply jquery click handlers (or others like hover or whatever) when you have constantly changing page content?

UPDATE: Event Delegation appears to be the key, but this code still doesn't work for some reason:

    $('.delete_button').on("mouseenter","img",function() { alert("DLH"); });

It DOES work if I attach it to $(document) as suggested below, but am I not able to attach it more specifically as in the documentation? Is there a performance hit for attaching it to document?

도움이 되었습니까?

해결책 2

Thanks to Kahnh and Arun (who commented, not answered so I can't select them :( ), I found the answer. I needed to look at Event Delegation which means use .on('click' instead of .click(). Additionally I found that delegation does't work with classes only IDs or document itself. Combining these together, I now have a way to un-clutter my code and make it work without nasty hacks. Thanks guys!

다른 팁

There are a few things wrong in your code:

  1. $('edit_button') is nothing you need to add a . for the class $('.edit_button')
  2. <div id='area1'><div class='edit_button></div></div> class edit_button has no closing'

here a cleaner working example : http://jsfiddle.net/LpDD4/

<div id="area1"><div class="edit_button">one</div></div>
<div id="area2"><div class="edit_button">two</div></div>
<div id="area3"><div class="edit_button">three</div></div>


$(document).ready(function(){
    $('.edit_button').on('click', function() {
        alert('test '+$(this).parent('div').attr('id'));
    });
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top