我有一个带有id="modal"的<div>,它是用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');第二个代码块似乎适用于原始元素,但它不是由新的动态生成的元素触发的。
发布于 2012-10-11 07:31:21
您需要delegate the event到页面中最接近的静态祖先元素(另请参阅"Understanding Event Delegation")。这仅仅意味着,绑定事件处理程序的元素在绑定处理程序时必须已经存在,因此对于动态生成的元素,必须允许事件冒泡并进一步处理它。
执行此操作的方法是jQuery .on方法(对于旧版本的jQuery,则为.delegate方法)。
// 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');
});发布于 2012-10-11 07:26:49
之所以发生这种情况,是因为您在连接事件之后添加了input元素。试试.on
$('body').on('keyup', 'input', function() {
handler = $(this).val();
name = $(this).attr('name');
});使用.on将确保keyup事件连接到最初位于页面上的输入,以及以后动态添加的任何输入。
发布于 2012-10-11 07:29:02
当您动态更改DOM时,jQuery不会将事件处理程序附加到它们。您需要使用on() and delegated events
对于您的输入项,您需要类似以下内容:
$("<parentSelector>").on("keyup", "input", function() {
handler = $(this).val();
name = $(this).attr('name');
})其中parentSelector是DOM中比输入元素更高的元素,并且是页面加载时存在的元素,可能是表单ID或其他什么。
https://stackoverflow.com/questions/12829963
复制相似问题