简体   繁体   中英

jQuery on click for dynamic element triggering when not clicked

I have a button that I am appending to the page. When that button is clicked, it should run some code.

Instead of triggering only when that button is clicked, any clicks on the page triggers it.

I've been able to replicate the issue with only a few lines of code, see the JSFiddle linked.

var myButton = '<div id="myButton">Do Not Click Me</div>';
$('#parent').html(myButton);

jQuery(document).on('click', jQuery('#myButton'), function (e) {
    alert('marco');
});

https://jsfiddle.net/aj4u1y9n/

How can I make the alert run only when the button is clicked?

Don't use a jQuery selector here:

jQuery(document).on('click', jQuery('#myButton'), function (e)

Instead, do:

$(document).on('click', '#myButton', function (e)

Example:

 var myButton = '<div id="myButton">Do Not Click Me</div>'; $('#parent').html(myButton); $(document).on('click', '#myButton', function(e) { alert('marco'); }); 
 #myButton { background: #8888ff; padding: 1em; width: 4em; margin-left: 4em; margin-top: 4em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> </div> 

By the way, your code could be simplified to this:

 var myButton = '<div id="myButton">Do Not Click Me</div>'; $('#parent').html(myButton); $('#myButton').click(function() { alert('marco'); }); 
 #myButton { background: #8888ff; padding: 1em; width: 4em; margin-left: 4em; margin-top: 4em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> </div> 

BTW , don't switch between the selectors jQuery and $ , use one or the other.

The way you wrote the click listener, you actually listen for clicks on the whole document. Have a look at the jQuery API:

for more information.

You can achieve what you wish like that:

var $myButton = $('<div id="myButton">Do Not Click Me</div>');
$myButton.click(function (e) {
    alert('marco');
});
$('#parent').append($myButton);

Explanation: You can add the click listener before you insert the element into the DOM. Searching it again in the DOM for adding a click handler is just unnecessary.

Fiddle: https://jsfiddle.net/bkbczLug/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM