我有一个 <div>
与 id="modal"
使用 jQuery 动态生成 load()
方法:
$('#modal').load('handlers/word.edit.php');
word.edit.php
包含一些输入元素,它们被加载到模态 <div>
中.
使用 jQuery 的 keyup
方法我可以在事件触发后捕获输入值,但是
当元素动态添加到模态 div 时,事件不再在用户输入文本时触发。
哪个 jQuery 方法支持处理由动态创建的元素触发的事件?
创建新输入元素的代码是:
$('#add').click(function() {
$('<input id="'+i+'" type="text" name="translations' + i + '" />')
.appendTo('#modal');
获取用户值的代码是:
$('input').keyup(function() {
handler = $(this).val();
name = $(this).attr('name');
第二个代码块似乎适用于原始元素,但它不会被新的动态生成的元素触发。
最佳答案
您需要delegate the event到页面中最近的静态祖先元素(另请参阅 "Understanding Event Delegation" )。这只是意味着,绑定(bind)事件处理程序的元素在绑定(bind)处理程序时必须已经存在,因此对于动态生成的元素,您必须允许事件冒泡并进一步处理它。
jQuery .on
方法是执行此操作的方法(或 .delegate
对于旧版本的 jQuery。)
// If version 1.7 or above
$('#modal').on('keyup', 'input', function() {
handler = $(this).val();
name = $(this).attr('name');
});
或者在旧版本中
// 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');
});
关于javascript - 动态生成的元素触发的事件不会被事件处理程序捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12829963/