简体   繁体   中英

jQuery trigger click (element.click()) on dynamically created button

I know that with on('click') for dynamically created elements, I must first use a parent element that existed in the DOM For example parent.on('click', child, function(){});

However now my task is to trigger a click to a dynamically created button.

I tried $('#button_' + id).click() and $('#button_' + id, '#parentContainer').click() but they didn't work.

.trigger('click') instead?

 $("#container").append('<div id="parentContainer"></div>'); $("#parentContainer").append("<button>Test</button>"); $("#container").on('click', '#parentContainer button', function(){ $("#container").after("click!<br>"); }); $("button").trigger("click"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"></div> 

Why don't you try

$('#button_' + id).on('click',function(){
   //your click event
});

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