我试图在第一次单击后禁用 li 单击事件。本质上是为了阻止数组数据翻倍。每次点击都正常。我目前的方法似乎不起作用。我还需要禁用其他 li 一旦第一个有 :)
谢谢
JS代码是:
$('#eventType ul li').click(function(e) {
e.preventDefault();
var value = $(this).attr('value');
answers.push(value);
// Below isn't working
$(this).click(function() {
return false;
});
console.log(answers);
});
Run Code Online (Sandbox Code Playgroud)
你需要使用one:
$('#eventType ul li').one('click',function(){
//your code here
});
Run Code Online (Sandbox Code Playgroud)
这个事件只会被触发一次
更新
你可以使用 $.off()
$('#eventType ul li').one('click',function(){
//your code here
$('#eventType ul li').off('click');
});
Run Code Online (Sandbox Code Playgroud)
jQuery 只是 JavaScript,因此您可以轻松添加所需的行为
// basic jQuery plugin boilerplate
$.fn.once = function once(eventType, f) {
// this = the selected elements
return this.each(idx, elem) {
// create reference to jQuery-wrapped elem
var $elem = $(elem);
// add event listener for eventType
$elem.on(eventType, function(event) {
// call the event handler
return f(event);
// remove the event handler
$elem.off(eventType, f);
});
});
};
Run Code Online (Sandbox Code Playgroud)
用法看起来像这样
$('#eventType ul li').once('click', function(event) {
console.log("you will only see this once");
});
Run Code Online (Sandbox Code Playgroud)
然而,这显然是一个常见的需求,因此它已经存在于 jQuery 中。它被称为$.one。随着 API 的增长,您可能不知道此类过程的存在。这个答案的存在是为了告诉你,你可以用你的大脑来编程你想要的东西或者特定库中可能缺少的东西。这减少了您对库创建者引入所需功能的依赖。
编辑
在注释中,您询问在单击第一个 LI 后是否可以对所有其他 LI 元素禁用事件处理程序。这里的麻烦在于 jQuery 使用隐式迭代,这意味着当你调用时,jQuery 将为每个$('li').on('click', ...)LI绑定一个onclick事件处理程序。
解决这个问题的一个更好的方法是使用 jQuery 的事件委托
// basic jQuery plugin boilerplate
$.fn.once = function once(eventType, f) {
// this = the selected elements
return this.each(idx, elem) {
// create reference to jQuery-wrapped elem
var $elem = $(elem);
// add event listener for eventType
$elem.on(eventType, function(event) {
// call the event handler
return f(event);
// remove the event handler
$elem.off(eventType, f);
});
});
};
Run Code Online (Sandbox Code Playgroud)
$('#eventType ul li').once('click', function(event) {
console.log("you will only see this once");
});
Run Code Online (Sandbox Code Playgroud)
这会将事件侦听器委托给子 LI,但一旦单击其中一个 LI,事件处理程序将被删除(因为我们使用该$.one过程进行委托)。
尝试单击一个 LI,您将在控制台中看到一条消息。当您单击第二个 LI 时,不会发生任何事情,因为事件处理程序已被删除。