javascript 由动态生成的元素触发的事件不会被事件处理程序捕获

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12829963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:13:03  来源:igfitidea点击:

Events triggered by dynamically generated element are not captured by event handler

javascriptjquery

提问by redbull330

I have a <div>with id="modal"generated dynamically with the jQuery load()method:

我有一个<div>使用id="modal"jQueryload()方法动态生成的 with :

$('#modal').load('handlers/word.edit.php');

word.edit.phpcontains a few input element, which are loaded into a modal <div>.

word.edit.php包含一些输入元素,它们被加载到一个 modal 中<div>

Using jQuery's keyupmethod I can capture the input values after an event fires, but when the elements are added dynamically to the modal div, the event no llonger fires when the user enters their text.

使用 jQuery 的keyup方法我可以在事件触发后捕获输入值,但是当元素被动态添加到模态 div 时,当用户输入文本时,事件不再触发。

Which jQuery method supports handling events triggered by dynamically created elements?

哪个 jQuery 方法支持处理由动态创建的元素触发的事件?

The code for creating the new input elements is:

创建新输入元素的代码是:

$('#add').click(function() {
    $('<input id="'+i+'" type="text" name="translations' + i + '"  />')
      .appendTo('#modal');

The code for capturing the user's values is:

捕获用户值的代码是:

$('input').keyup(function() {
    handler = $(this).val();
    name = $(this).attr('name');

This second code block seems to work for the original elements, but it is not fired by the new dynamically generated elements.

第二个代码块似乎适用于原始元素,但它不会被新的动态生成元素触发。

采纳答案by Sushanth --

You need to delegate the eventto the closest static ancestor element within the page (see also "Understanding Event Delegation"). This simply means, the element where you bind your event handler must already existat the time the handler is bound, so for dynamically generated elements you must allow the event to bubble up and handle it further up.

您需要将事件委托给页面内最近的静态祖先元素(另请参阅“了解事件委托”)。这只是意味着,绑定事件处理程序的元素在绑定处理程序时必须已经存在,因此对于动态生成的元素,您必须允许事件冒泡并进一步处理。

The jQuery .onmethod is the way to do this (or .delegatefor older versions of jQuery.)

jQuery.on方法是执行此操作的方法(或.delegate对于旧版本的 jQuery。)

// If version 1.7 or above

$('#modal').on('keyup', 'input', function() {
    handler = $(this).val();
    name = $(this).attr('name');
});

Or in older versions

或者在旧版本中

// If version 1.6 or below

// note the selector and event are in a different order than above
$('#modal').delegate('input', 'keyup', function()
{
    handler = $(this).val();
    name = $(this).attr('name');
});

回答by Gromer

This is happening because you're adding the input element afteryou wired up the event. Try .on:

发生这种情况是因为您在连接事件添加了 input 元素。尝试.on

$('body').on('keyup', 'input', function() {
    handler = $(this).val();
    name = $(this).attr('name');
});

Using .onwill make sure the keyupevent is wired up to inputs that are on the page originally, as well as any that are added later dynamically.

使用.on将确保keyup事件连接到页面上最初的输入,以及稍后动态添加的任何输入。

回答by ernie

When you dynamically change the DOM, jQuery won't attach event handlers to them. You need to use on() and delegated events

当您动态更改 DOM 时,jQuery 不会将事件处理程序附加到它们。您需要使用on() 和委托事件

For your input items, you'll need something like:

对于您的输入项,您将需要以下内容:

$("<parentSelector>").on("keyup", "input", function() { 
    handler = $(this).val();
    name = $(this).attr('name');
})

Where the parentSelector is something higher in the DOM than the input element, and an element that exists at page load, maybe the form ID or something.

parentSelector 在 DOM 中比输入元素更高,并且在页面加载时存在一个元素,可能是表单 ID 或其他东西。

回答by Carlos Pereira

Function binds are made ??in page load. To work on elements created dynamically using the function live (). Example:

函数绑定是在页面加载时进行的。处理使用函数 live () 动态创建的元素。例子:

$ ("p"). live ("click", function () {
    // Your function
});

回答by i--

If you need to capture changes for all of the form elements, particularly select boxes, I know they are not mentioned here, but it is helpful to know, use the following code:

如果您需要捕获所有表单元素的更改,特别是选择框,我知道这里没有提到它们,但是知道它会很有帮助,使用以下代码:

$(document).on('change', ':input', function () {
   alert('value of ' + $(this).attr('name') + ' changed')
});

This should cover all input, textarea, select, checkbox, radio, etc.

这应涵盖所有inputtextareaselectcheckboxradio,等。