单击带有常规 javascript 的 div

click on a div with regular javascript (单击带有常规 javascript 的 div)

本文介绍了单击带有常规 javascript 的 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jquery 甚至在像 DIV 这样通常不可点击的东西上也附加了一个 click 方法.这可能很棒,因为有些事情会对此做出反应.如何在没有 Jquery 的情况下使用普通的旧 javascript 单击"任何旧的常规 DIV?

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 中发布的区域.我正在使用可以在热键上运行一些 javascript 的 chrome 扩展程序.我写了一个jquery版本var x = $('div[guidedhelpid="sharebox"]');x.click();

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 库似乎只加载大约 1/4 的时间.不知道为什么,所以我想我会尝试用普通的 JS 来制作它.至于处理程序,谷歌自己的代码可以很好地拦截和处理点击,它在 Jquery 版本中工作.所以我只想有效地做同样的事情.

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 是在内部向上还是向下移动 DOM,直到找到第一个认为可点击的对象?

does Jquery internally go up or down the DOM until it finds the first think clickable?

更新鉴于此,我正在寻找错误的方向,并且真的只需要找到正确的元素来关注(在 JQUERY 中).

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).

推荐答案

如果你只想给元素绑定一个函数,你可以使用

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
}

但是如果你需要附加多个事件,你应该使用addEventListener(除了IE之外的所有东西)和attachEvent(IE)

but if you need to attach more than one event, you should use addEventListener (eveything except IE) and attachEvent (IE)

if(element.addEventListener) {
element.addEventListener("click", function() {});
} else { 
element.attachEvent("onclick", function() {})
}

这篇关于单击带有常规 javascript 的 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:单击带有常规 javascript 的 div

基础教程推荐