click on a div with regular javascript

2020-04-07 15:55发布

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?

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();

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.

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

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

5条回答
Deceive 欺骗
2楼-- · 2020-04-07 16:22

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)

if(element.addEventListener) {
element.addEventListener("click", function() {});
} else { 
element.attachEvent("onclick", function() {})
}
查看更多
够拽才男人
3楼-- · 2020-04-07 16:26

Here's an article by 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().

查看更多
看我几分像从前
4楼-- · 2020-04-07 16:26
var divElement = document.getElementById('section');

divElement.addEventListener('click', function () {
  alert('div clicked');
},false);
查看更多
贼婆χ
5楼-- · 2020-04-07 16:37

The click() function is built in JavaScript, not jQuery.

HTMLElementObject.click()

Source.

查看更多
Evening l夕情丶
6楼-- · 2020-04-07 16:41
var d = document.getElementById("test");
d.onclick = function(){alert('hi');};
查看更多
登录 后发表回答