我正在尝试创建一个表单输入,仅当前一个字段的值为 true 时,才会将一个空输入字段附加到一系列的末尾。 我已经走了很远,但我在重新绑定(bind)最后一个元素时遇到了麻烦。
function removeEmpty(){
$('p:last').remove()
}
function init(){
$('p:last input').focus(function(event){
$(event.target).closest('p').append("<p class=''><label>middlename: </label><input></input></p>")
init()
})
$('p:last input').blur(function(event){
console.log($(event.target).val())
if(!$(event.target).val()){
removeEmpty()
}
})
}
init()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="first">
<label>middlename: </label><input></input>
</p>
最佳答案
您可以改用事件委托(delegate)
。
不要使用这个:
$('p:last input').focus(...);
$('p:last input').blur(...);
你可以使用这个:
$('body').on("focus","p:last input", function() { ... });
$('body').on("blur","p:last input", function() { ... });
我已经更新了您的代码:
function removeEmpty(){
$('p:last').remove()
}
function init(){
$("body").on('focus','p:last',function(event){
var target = $(event.target);
target.closest('p').append("<p class=''><label>middlename: </label><input></input></p>");
target.one("blur",function() {
if(!target.val()) {
removeEmpty();
}
});
})
}
init()
参见http://api.jquery.com/on/ 和 http://api.jquery.com/one/
我猜是这个FIDDLE就是你想要的!
关于javascript - 如何取消绑定(bind)非最后一个元素上的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30758133/