如何从类中删除事件监听器?

问题描述 投票:0回答:1

我在删除事件监听器时遇到问题。运行此脚本时出现changeGirl.off("click") is not a function错误。我需要删除事件监听器,其他所有东西都运行良好。有什么想法吗?

$( document ).ready(function() {
	$(".changeGirl").each(function() {
		var changeGirl = this;
		
		changeGirl.addEventListener("click",function() {
			if (window.XMLHttpRequest) {
				xmlhttp=new XMLHttpRequest();
			} else {
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState==4 && xmlhttp.status==200) {
					changeGirl.innerHTML = xmlhttp.responseText;
					changeGirl.off("click");
				}
			}
			xmlhttp.open("GET","getUsers.php?girls="+$(this).attr("data-position"),true);
			xmlhttp.send();
		});
	});
});
javascript
1个回答
-1
投票

您可以尝试从addEventListener中提取函数并将其命名为yourFunction,然后使用removeEventListener:

changeGirl.addEventListener("click", yourFunction);
changeGirl.removeEventListener("click", yourFunction, true);
© www.soinside.com 2019 - 2024. All rights reserved.