且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态创建元素的事件监听器

更新时间:2022-12-27 11:05:02

您可以使用.on()预先注册:

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.