[英]How do I unbind events on elements that are not the last
我正在尝试进行一个表单输入,仅在前一个字段的值为true时,才将一个空的输入字段附加到序列的末尾。 我已经走得很远了,但是在重新绑定最后一个元素时遇到了麻烦。
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>
您可以改用event delegation
。
而不是使用此:
$('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是您想要的!
问题是因为您正在使用append
而不是之后...使用此
$(event.target).closest('p')
.after("<p class=''><label>middlename:</label><input></input></p>")
init()
另外,要选择不是最后一个jQuery('p').filter(':not(:last)')
:使用jQuery('p').filter(':not(:last)')
而且removeEmpty
必须像
function removeEmpty(){
jQuery('p').filter(':not(:first)').find('input').each(function(){
if(!($(this).value)) $(this).closest('p').remove();
});
}
完整的代码在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.