动态创建元素的事件监听器 [英] Event Listener for Dynamically Created Elements
问题描述
如何为动态创建的元素提供事件侦听器?在下面的示例中,所有这些代码执行完后,变量term_num就会递增1(term_num ++),因此,每次调用#abtn click事件时,都会创建一个新的div元素"term_ [term_num]".如何为这些新div中的每个div提供点击事件侦听器?
How do I give a dynamically created element an event listener? In the example below, AFTER all this code execute the variable term_num increments up by one (term_num++) so every time the #abtn click event is called, a new div element "term_[term_num]" is created. How do I give each of these new divs a click event listener?
$( document ).ready(function() {
$( "#abtn" ).click(function( event ) {
var newterm = '<div id=\'term_'+term_num+'\'>'+term+' </div>';
var term = document.getElementById("term_input").value;
$('#terms').after(newterm);
推荐答案
You can just register it in advance with .on()
: Live demo (click).
$(document).on('click', 'some-selector', function() {
});
或创建dom元素newTerm
,然后将其附加并直接附加功能: 实时演示(点击).
or create the dom element newTerm
before appending it and attach the function directly: Live demo (click).
var $newTerm = $(newTerm);
$newTerm.click(function() {
});
由于要添加到元素中的选择器是动态ID,因此我建议在这里使用第二种方法.如果要向生成的元素添加类,以便可以将.on
委派给它们,请使用.on
.效率更高.
Since the selector you're adding to the element is a dynamic id, I'd recommend going with the second approach here. If you want to add a class to the generated elements so that you can delegate .on
to them, use .on
. It's more efficient.
这篇关于动态创建元素的事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!