[英]How do I unbind events on elements that are not the last
I'm trying to make a form input that appends an empty input field to the end of a series, only if the value of the previous field is true. 我正在尝试进行一个表单输入,仅在前一个字段的值为true时,才将一个空的输入字段附加到序列的末尾。 I'v gotten pretty far but I'm having trouble re-binding the last element.
我已经走得很远了,但是在重新绑定最后一个元素时遇到了麻烦。
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>
You could use the event delegation
instead. 您可以改用
event delegation
。
Instead of using this: 而不是使用此:
$('p:last input').focus(...);
$('p:last input').blur(...);
you could use this: 您可以使用此:
$('body').on("focus","p:last input", function() { ... });
$('body').on("blur","p:last input", function() { ... });
I've updated your code: 我已经更新了您的代码:
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()
See http://api.jquery.com/on/ and http://api.jquery.com/one/ 参见http://api.jquery.com/on/和http://api.jquery.com/one/
The problem is because you are using append
instead of after... Use this 问题是因为您正在使用
append
而不是之后...使用此
$(event.target).closest('p')
.after("<p class=''><label>middlename:</label><input></input></p>")
init()
In addition, To select the p that is not the last: use jQuery('p').filter(':not(:last)')
另外,要选择不是最后一个
jQuery('p').filter(':not(:last)')
:使用jQuery('p').filter(':not(:last)')
And the removeEmpty
must be somthing like 而且
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.