单击带有常规 javascript 的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9220486/
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
click on a div with regular javascript
提问by klumsy
jquery attaches a click method on even things that aren't typically clickable like a DIV. this can be great because some things respond to that. How can i "click" on any old regular DIV using plain old javascript without Jquery?
jquery 甚至在像 DIV 这样通常不可点击的东西上附加了一个 click 方法。这可能很棒,因为有些事情会对此做出反应。我如何在没有 Jquery 的情况下使用普通的旧 javascript “点击”任何旧的常规 DIV?
what i am trying to do is trigger clicking on the area where the user can post in Jquery. I'm using a chrome extension that can run some javascript on a hotkey. I wrote a jquery version var x = $('div[guidedhelpid="sharebox"]'); x.click();
我想要做的是触发点击用户可以在 Jquery 中发布的区域。我正在使用可以在热键上运行一些 javascript 的 chrome 扩展。我写了一个 jquery 版本 var x = $('div[guidedhelpid="sharebox"]'); x.click();
which works fine, other than it seems that the jquery library only loads about 1/4 of the time. not sure why, so i figured i'd try to make it in plain JS. As for the handler, googles own code is intercepting and processing the clicks fine, and it works in the Jquery version. so i just want to effectively do the same thing.
效果很好,除了 jquery 库似乎只加载了大约 1/4 的时间。不知道为什么,所以我想我会尝试用普通的 JS 来制作它。至于处理程序,谷歌自己的代码拦截和处理点击很好,它在Jquery版本中有效。所以我只想有效地做同样的事情。
does Jquery internally go up or down the DOM until it finds the first think clickable?
Jquery 是否在内部向上或向下移动 DOM,直到它找到第一个可点击的想法?
update in light of it, i was looking in the wrong direction, and really just needed to find the right element to focus on (in JQUERY).
根据它更新,我看错了方向,实际上只需要找到要关注的正确元素(在 JQUERY 中)。
回答by nicosantangelo
If you just want to bind one function to the element, you could use
如果您只想将一个函数绑定到元素,则可以使用
var element = document.getElementById("el"); //grab the element
element.onclick = function() { //asign a function
//code
}
but if you need to attach more than one event, you should use addEventListener
(eveything except IE) and attachEvent
(IE)
但是如果你需要附加多个事件,你应该使用addEventListener
(除IE之外的所有内容)和attachEvent
(IE)
if(element.addEventListener) {
element.addEventListener("click", function() {});
} else {
element.attachEvent("onclick", function() {})
}
回答by Jivings
回答by Jason
Here's an articleby John Resig (creator of jQuery) on how to do this very thing. It's basically his entry into a contest(that he won) on how to rewrite addEvent()
.
这是John Resig(jQuery 的创建者)撰写的关于如何做这件事的文章。这基本上是他参加了一场关于如何重写addEvent()
.
回答by SynXsiS
var d = document.getElementById("test");
d.onclick = function(){alert('hi');};
回答by yeraycaballero
var divElement = document.getElementById('section');
divElement.addEventListener('click', function () {
alert('div clicked');
},false);