javascript - 如何取消绑定(bind)非最后一个元素上的事件

标签 javascript jquery

我正在尝试创建一个表单输入,仅当前一个字段的值为 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/

相关文章:

javascript - 如何在 Oracle JET ojTable 中选择一行?

javascript - 为什么日期选择器的值没有改变?

javascript - Nativescript WebView,在 Android 上导航回来时防止重新加载

javascript - 查找数组对象中的中间数字

javascript - 使用 REACT 可视化文本区域中的 onkeypress 换行符

javascript - 在 Angular2 应用程序中渲染 JSON 对象会导致 "object Object"

jquery - 设置图像大小限制并根据需要调整图像大小

jQuery 加载带有图像的 HTML 将错误呈现到控制台

javascript - 调整浏览器大小时 Modernizr 媒体查询不起作用

javascript阅读更多功能?