JQuery trigger does not fire after cloning

I have a div in my code, and when I clone it, do not direct fire at the event. Here is the code;

<div id="draggable" onclick="alert(1);" class="ui-widget-content drag"> <p>Drag me to my target</p> </div> <div id="here"> </div> <script type="text/javascript"> $("#draggable").clone().removeAttr("id").attr('id', 'draggable2').appendTo("#here"); $("#draggable2").trigger('onclick'); </script> 

When I click on a cloned item, it lights up with a normal event.

If I modify the script to run the source element, it works fine:

 <script type="text/javascript"> $("#draggable").clone().removeAttr("id").attr('id', 'draggable2').appendTo("#here"); $("#draggable").trigger('onclick'); </script> 

Also the bind function works fine:

 <script type="text/javascript"> $("#draggable").clone().removeAttr("id").attr('id', 'draggable2').appendTo("#here"); $("#draggable2").bind('click', function () { alert('2'); }); $("#draggable2").trigger('click'); </script> 

Does anyone have an idea on how to launch the "standard" onclick of the cloned element immediately after cloning.

+4
source share
2 answers

To clone the AND element of its event, you must pass "true" as the first argument. To convey events to your children, you must also convey "truth" as your second argument.

 $myClone = $('#element').clone( true, true ); 

http://api.jquery.com/clone/

+20
source

This is a fragile approach from the very beginning. You have a function to create a clone, and then you have a function to execute after cloning. Why not just call this function after cloning? Make a reusable function that can be called from click bindings or called directly from the clone function.

If absolutely necessary, you can simply use $(selector).click() , which will fire the click event.

[edit: I didn’t know about the need to convey the “truth” according to Fauntleroy's answer, so without this advice my approach would not work either. But the general advice “this is probably a bad approach” is worth it)

0
source

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


All Articles