简体   繁体   English

如果已经存在香草 javascript 或 jquery,如何检查和删除事件

[英]How to check and remove the event if already exist with vanilla javascript or jquery

I am performing a task where i need to reload the function again but i do not want to add same event with same function so i need to listen the elements events first and if it is not exist i need to add it if event already exist i need to prevent it from happening.我正在执行一项任务,我需要再次重新加载 function 但我不想添加具有相同 function 的相同事件,所以我需要先监听元素事件,如果它不存在,我需要添加它如果事件已经存在我需要防止它发生。

My DOM i like this.我的 DOM 我喜欢这个。

<a href='#clicked' id='toggle_bars' data-gonext='1'>next</next>

$('#toggle_bars').click(function(){
// some argument
})

// for page one
<a href='#clicked' id='toggle_bars_again' data-goback='1'>next</next>
$('#toggle_bars_again').click(function(){
// some argument
})
// for page one

i do not want to reload the page when user click on #toggle_bars he need to go back and reload its function when i load the #toggle_bars_again the function repeat itself i want to listen its events and prevent it from happening. i do not want to reload the page when user click on #toggle_bars he need to go back and reload its function when i load the #toggle_bars_again the function repeat itself i want to listen its events and prevent it from happening.

i also use methods like return false event.preventDefault() event.stopPropogation我还使用return false event.preventDefault() event.stopPropogation等方法

FYI: I know that this is may be a bad practice but this is a very old code-base and i do not want to redo it again.仅供参考:我知道这可能是一种不好的做法,但这是一个非常古老的代码库,我不想再重做一次。

"he need to go back and reload its function when I load the #toggle_bars_again the function repeat itself I want to listen its events and prevent it from happening." “当我加载#toggle_bars_again function 时,他需要重新加载 go 并重新加载它的 function,并防止它重复发生。” what are you trying to say its not clear.你想说什么不清楚。 if you want to prevent the page from reloading remove href and in here:如果您想阻止页面重新加载,请删除 href 并在此处:

   $('#toggle_bars').click(function(event){
        event.preventDefault()
    });

I don't know if it's clearly what you search, but if you need to connect the same event again on the same element, you can do something like that:我不知道你搜索的内容是否明确,但如果你需要在同一个元素上再次连接同一个事件,你可以这样做:

$("element").off("click").on("click", function() {})

And if it's on an other element, just do an off on the first and then connect your event to the second element如果它在另一个元素上,只需在第一个元素上关闭,然后将您的事件连接到第二个元素

Jquery's one() method could be a solution too Jquery 的 one() 方法也可能是一个解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM