所以我有这个场景
当我加载表单时,我最初有一个文本类型的输入。
该输入附加了“keyup”事件,如果用户输入了超过 5 个字符,则会在输入元素之后注入(inject)新的输入文本,并从当前元素解除 keyup 事件的绑定(bind)。
HTML:
<form>
<input id="input1" type="text" class="email-input" />
</form>
JQUERY:
$('.email-input').on({
keyup: function() {
if (this.value.length > 5)
{
var newInput = $("<input type='text' class='email-input' />");
$('form').append(newInput);
$(this).unbind('keyup');
}
}
});
我希望新创建的元素具有与原始创建的元素相同的功能。我该如何实现这一目标?
最佳答案
将事件委托(delegate)给 FORM:
$('form').on({
keyup: function() {
if($(this).data('unbind')) return;
if (this.value.length > 5)
{
var newInput = $("<input type='text' class='email-input' />");
$('form').append(newInput);
//used to filter event, you cannot unbind here delegated event just for specific element
$(this).data('unbind',true);
}
}
},'.email-input');
关于jQuery:动态地将 keyup 附加到动态创建的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546051/