javascript - JQuery 更改事件不是每次都会触发

标签 javascript jquery html

所以这是一个非常奇怪的问题,如果我的事件根本没有被触发,我就会发现一些问题。但我有以下代码,每当选中复选框时就会调用函数:

$('input:checkbox').change(
        function(){
            filterByOptions();
});

filterByOptions 基本上根据选中的复选框调整页面上的内容。现在我想要的是每次单击复选框时调用此函数。但这只是有时发生(我想说大约 50% 的时间)。我尝试将此代码放在页面的不同部分,包括放在 $(document).ready(function() { 方法中以及页面末尾的单独脚本标记中。但问题仍然存在。

有人可以提供解决方案或告诉我我可能做错了什么吗?

最佳答案

您在下面的评论中指出您正在动态创建新元素,这会导致事件绑定(bind)出现问题。解决方案是使用 event delegation ,这是您在高级祖先元素上设置事件的位置,该事件将始终存在于文档中,然后,因为大多数事件都会向上冒泡到其祖先,所以您可以在那里处理事件。但是,在处理事件时,您可以检查事件起源的元素并据此做出决策。

接下来,不要将 change 事件与复选框一起使用。使用click 事件。 change 事件旨在指示元素的发生更改,当您单击复选框时,您不会更改其,您正在更改其 checked 属性。要更准确地捕获点击,请使用 click 事件。

是的,代码应该位于 document.ready() 回调内部。

此外,让回调函数仅包含对另一个函数的调用是没有意义的。只需将 filterByOptions 设置为回调即可。

最后,JQuery 建议使用 on() 事件绑定(bind)方法:

$(function(){
  // Set up the event on the ancestor
  $('#parent').on("click", filterByOptions);  

  // Now, lets dynamically create a new checkbox.
  // This element will be inserted into the element that is set up to handle bubbled events,
  // so the new element will immediately respond to events even though it wasn't specifically
  // bound.
  $("#parent").append('<input type="checkbox" name="chk4" value="4" id="chk4" class="handle"><label for="chk4">Box 4</label>');

  // All event handlers are automatically passed a reference
  // to the event object that triggered them, it is a good idea
  // to set up a named argument to reference it.
  function filterByOptions(evt){
    // Check to see if the event originated at an element you care about
    // This is easily accomplished by checking for the class we set up earlier
    if(evt.target.classList.contains("handle")){
  
      // Do whatever you need to here, including checking if the box is or isn't checked
      console.log(evt.target.name + " was clicked and is now" + (evt.target.checked ? " " : " not ") + "checked.");     
    } 
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="parent">
  <!-- If we give the elements that need handling a common class, it will be easier later-->
  <input type="checkbox" name="chk1" value="1" id="chk1" class="handle"><label for="chk1">Box 1</label>
  <input type="checkbox" name="chk2" value="2" id="chk2" class="handle"><label for="chk2">Box 2</label>
  <input type="checkbox" name="chk3" value="3" id="chk3" class="handle"><label for="chk3">Box 3</label>
</div>

关于javascript - JQuery 更改事件不是每次都会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116787/

相关文章:

javascript 表单验证空字段和错误输入

jquery - 垂直对齐似乎不起作用

jquery - 从具有相同类的 span 中获取文本

javascript - 为什么自闭合脚本元素不起作用?

JavaScript 浮点好奇心

javascript - 需要帮助对齐 Javascript 倒计时的结果

javascript - 为什么 getElementsByTagName 返回未定义?

javascript - 使用 javascript 在木瓜 dicom 查看器切片中进行分页

html - Css 下拉菜单向左折叠打开

javascript - 我想使用 javascript 单击网站上的所有 div 框