用普通的javascript点击一个div [英] click on a div with regular javascript

查看:70
本文介绍了用普通的javascript点击一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jquery附加了一个click方法,即使是像DIV那样通常不可点击的东西。这可能很棒,因为有些事情会对此作出反应。如何在没有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。我正在使用Chrome扩展程序,可以在热键上运行一些javascript。我写了一个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制作它。对于处理程序,googles自己的代码正在拦截和处理点击,并且它在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 (evething除了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆