javascript 有效地从 DOM 元素中删除 onmouseover 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18837719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove onmouseover event from DOM elements efficiently
提问by soupagain
I have an HTML page that contains many onmouseover events. These events are linked to a,img,td and div tags.
我有一个 HTML 页面,其中包含许多 onmouseover 事件。这些事件链接到 a,img,td 和 div 标签。
What is the most efficient Javascript way to remove all the onmouseover events, presuming the page has loaded.
假设页面已加载,删除所有 onmouseover 事件的最有效 Javascript 方法是什么。
I'm not using jQuery.
我没有使用 jQuery。
(the task is to remove unneeded tooltips when the page is accessed using touch devices)
(任务是在使用触摸设备访问页面时删除不需要的工具提示)
采纳答案by y0ruba
Just add a unique class to everything that has the mouseover event and then make a loop
只需为具有鼠标悬停事件的所有内容添加一个唯一的类,然后进行循环
get=document.getElementsByClassName("classhere");
for(i=0; i<get.length; i++){
get[i].removeEventListener("mouseover", yourFunction, false);
}
replace yourFunction
and classhere
, tell me if it works or not
替换yourFunction
和classhere
,告诉我它是否有效
回答by Yuriy Galanter
Since all your event handlers point to the same central function - you candisable tooltips inside of that function.
由于您的所有事件处理程序都指向同一个中央函数 - 您可以禁用该函数内的工具提示。
If this function handles both onmouseover
and onclick
events - you can check event.type
and disable tooltips only if it's equal mouseover.
如果此函数同时处理onmouseover
和onclick
事件 -event.type
只有当它相等时,您才能检查和禁用工具提示mouseover.
回答by Paul Nelson
A simple function looping through all the elements should do the trick. This one does it for all divs:-
一个循环遍历所有元素的简单函数应该可以解决问题。这对所有 div 都适用:-
function removeMouseOver() {
var divs = document.body.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
divs[i].onmoseover = function() {};
}
}
another way is to define the mouseover tooltip function as a var
另一种方法是将鼠标悬停工具提示函数定义为 var
var tooltip = function(){// put your tooltip code here };
var donothing = function(){};
//to turn tooltips on:-
onmouseoverfunc = tooltip;
//to turn tooltips off:-
onmouseoverfunc = donothing;
in the elements
在元素
document.getElementById('mydiv').onmouseover = function(){mouseoverfunc();};