javascript - Jquery 中继器,为什么 .keyup 和 .change 不会在第二项及之后触发?

标签 javascript jquery

.keyup 和 .change 仅在第一个输入中触发,但在我添加新项目后不会触发。添加新字段时有没有办法触发 .keyup 和 .change ?

http://jsfiddle.net/q8pcoaxf/

$('.field').on('change keyup',function() {
    alert('alert');
})

最佳答案

jQuery 选择器仅选择执行时出现在 DOM 中的那些元素。在旧版本的 jQuery 中,曾经有一个函数 .live(),它也可以绑定(bind)到稍后添加的给定选择器的任何元素,但它已被删除。

您可以做的是通过 .on() 绑定(bind)到 document,并使用附加选择器作为第二个参数。但请记住,这将在绑定(bind)事件的每个触发器上触发并检查选择器,因此出于性能原因,如果您可以缩小将添加到特定父级的元素的范围(例如您的情况下可能是表单) ,您绝对应该这样做,而不是绑定(bind)到文档。

On a sidenote: Binding to change and keyup will result in the callback function to be executed twice in this example case, because the alert window popping up will result in the input losing focus and therefore the change event being triggered as well.

// will bind on the document and be executed for all change and keyup events on any element that has the class "field"
$(document).on('change keyup', '.field', function() {
  alert('alert');
});

// let's say you had a form with the id #dynamic_inputs where the inputs are added to,
// this would be the preferable way to handle it:
//$('#dynamic_inputs').on('change keyup', '.field', function() {
//  alert('alert');
//});

function addNewInput() {
  var newInput = document.createElement('input');
  newInput.classList.add('field');
  document.body.appendChild(newInput);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addNewInput()">add new input</button><br>
<input class="field" />

关于javascript - Jquery 中继器,为什么 .keyup 和 .change 不会在第二项及之后触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56000810/

相关文章:

javascript - ng 类不工作。我哪里做错了?

javascript - JQuery Div 内容改变事件

javascript - 从复选框 onchange 事件中获取值

javascript - 从 header 获取 token 时,req.headers.split 不是函数

javascript - 在express中使用返回值发送到ajax成功

javascript - 如何使用 javascript/jquery 获取第一个 json 元素处 json 数组中所有键的值

javascript - jQuery每次循环问题

jquery - 带有可折叠页脚的 Bootstrap 布局

javascript - iframe onclick 动画或切换

javascript - 重置 tinymce 工具栏选择