[英]jQuery Not Binding to Newly-Created <input> Element
This is what I have: 这就是我所拥有的:
<script language="javascript">
$('#click').one('click', function () {
var html = '<input type="text" class="input-mini" id="new-input" />';
$(this).parent().append(html);
});
$('#new-input').on('keyup', function (e) {
alert('A key was pressed');
if (e.keyCode == 13) {
alert('Enter key pressed');
}
});
</script>
At the recommendation of other SO answers , I found that I should use on()
to bind dynamically created elements. 在其他SO答案的推荐下,我发现我应该使用
on()
绑定动态创建的元素。 What I want to happen is for an AJAX call to occur after the user presses the Enter key inside the <input>
with ID new-input
. 我想发生的是在用户按下ID为
new-input
的<input>
内的Enter键后发生AJAX调用。 However, nothing happens when any key is pressed at all. 但是,根本没有按下任何键。
What do I need to do in order to bind the keyup
method to the newly-appended <input>
element? 为了将
keyup
方法绑定到新添加的<input>
元素,我需要做什么?
Thanks 谢谢
.on()
does not always bind dynamically-created elements; .on()
并不总是绑定动态创建的元素。 it only does that if you pass a selector to listen inside of: 仅当您通过选择器以侦听以下内容时,它才会这样做:
$('some container').on('click', '.new-input', function() { ... });
Also, IDs must be unique; 此外,ID必须唯一。 you should use classes.
您应该使用类。
At the time that the keyup binding is created, there won't be a matching element on the dom - try moving the second binding inside the callback for the first: 创建keyup绑定时,dom上将没有匹配的元素-尝试将第二个绑定移到回调中的第一个绑定中:
<script language="javascript">
$('#click').one('click', function () {
var html = $('<input type="text" class="input-mini" />');
html.on('keyup', function (e) {
alert('A key was pressed');
if (e.keyCode == 13) {
alert('Enter key pressed');
}
});
$(this).parent().append(html);
});
</script>
jsFiddle Link : http://jsfiddle.net/qTd9c/ jsFiddle链接: http : //jsfiddle.net/qTd9c/
$('#click').one('click', function () {
var html = '<input type="text" class="input-mini" id="new-input" />';
$(this).parent().append(html);
$('#new-input').on('keyup', function (e) {
alert('A key was pressed');
if (e.keyCode == 13) {
alert('Enter key pressed');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.