JQuery event fails when adding new div

Ok, here is my javascript:

$().ready(function (){ $(".contact").hover(function (){ ... }); $(".contact").not('.contact[id="'+activeId+'"]').click(function (){ ... }); $(".contact_chooser_contact").click(function (){ ... $('.contacts').append('<div class="contact" id="'+id+'" title="'+phone+'">\ <div class="contact_img"><img src="src/default_face.png" width="64"/></div>\ <div class="contact_info" id="'+name+'">'+name+' <span class="sms_number">0</span></div>\ <div class="contact_last_sms">\ \ <!-- span class="last_sms_time"> echo $message[sizeof($message)-1]->time; </ -->\ </div>\ </div>'); ... }); }); 

Notice how in the contact_chooser_contact click handler I add another .contact to the .contacts, but now when I hover over this new β€œ.contact”, it doesn't do anything similar as intended. How can I fix this problem, I understand that it is because I havent resumed "$ (" contact "). Hover () after adding a new" .contact ", but is there an easier way?

+2
source share
2 answers

You need to bind the event to on () , using this will bind any element added to the DOM with the corresponding selector. The advantage of using on() over live() is that you can narrow the context to a specific container, not the entire document . In my example, I just use document as a context.

jQuery 1.7 use on ()

 $(document).on('mouseover', '.contact', function(){ ... }); 

Less than 1.7 , use delegate ()

 $(document).delegate('.contact', 'mouseover', function(){ ... }); 

Less than 1.4.2 , use live ()

 $('.contact').live('mouseover', function(){ ... }); 
+4
source

". contact" add an event when loading a document. after, the div added from the ".contact" event actually has no event. because the click event is not executed again.

you can do like this:

 function addDiv(div) { div.hover(function() { ... }); } $(function() { addDiv($(".contact")); $(".contact_chooser_contact").click(function (){ addDiv($('<div/>').addClass('.contact').attr({id:ID, title: TITLE}).append(...)); }); }); 
-1
source

Source: https://habr.com/ru/post/905925/


All Articles