我有一个ul的事件监听器:
$('body').on('click.submenu', '.top-level', subMenu);
有没有办法确保只添加一次?
原因是,当视口处于“移动”断点时,我只需要添加它,当它从桌面回到移动时,似乎有多个事件监听器。
答案 0 :(得分:2)
var body = $("body"); //Store for later use
if(!(body.data("EventAdded") === true)){ //Test if event was added
body.data("EventAdded", true) //If not, set EventAdded as true
.on('click.submenu', '.top-level', subMenu); //and add the event
}
答案 1 :(得分:1)
我唯一能想到的就是在添加监听器之前调用off
$('body').off('click.submenu', '.top-level', subMenu);
$('body').on('click.submenu', '.top-level', subMenu);