所以这是一个非常奇怪的问题,如果我的事件根本没有被触发,我会出错。但是我有以下代码,只要选中复选框,就会调用一个函数:
$('input:checkbox').change(
function(){
filterByOptions();
});
filterByOptions基本上根据选中的复选框调整页面上的内容。现在,我想要的是每次单击复选框时都调用此函数。但这只是偶尔发生(我想说有50%的时间)。我尝试将这段代码放在页面的不同部分,包括$(document).ready(function() {
方法和页面末尾的单独脚本标记中。但是问题仍然存在。
有人可以提供解决方案或告诉我我可能做错了什么吗?
答案 0 :(得分:2)
您已经在下面的注释中指示您正在动态创建新元素,这将导致事件绑定问题。解决方案是使用 event delegation ,在该位置上,您可以在高级祖先元素上设置事件,该事件将始终存在于文档中,然后,因为大多数事件冒泡直到他们的祖先,您在那里处理事件。但是,在处理事件时,您可以检查事件起源的元素并据此做出决定。
接下来,不要将change
事件与复选框一起使用。使用click
事件。 change
事件旨在表示元素value
的更改,当您单击复选框时,您没有更改其value
,而是更改了其checked
属性。要更准确地捕获点击,请使用click
事件。
是的,代码应该在document.ready()
回调中。
此外,让回调函数仅包含对另一个函数的调用也没有意义。只需进行filterByOptions
的回调即可。
最后,JQuery建议使用 on()
方法进行事件绑定:
$(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>
答案 1 :(得分:-1)
也许您可以仔细检查是否导入了jquer js文件?您可以在日志中查看是否返回错误。希望我能帮忙