Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

pure javascript equivalent of jquery click()?

I am building a small app which captures mouse clicks. I wrote the prototype in jquery but, since it is a small app focusing on speed, embedding jquery to use just one function would be an overkill.

I tried to adapt this example from JavascriptKit:

document.getElementById("alphanumeric").onkeypress=function(e){  
    //blah..blah..blah..  
}

but it didn't work when I tried

document.getElementsByTagName("x").onclick

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Say you have a list of p tags you would like to capture the click for the p tag:

var p = document.getElementsByTagName("p"); 
for(var i=0; i<p.length; i++){ 
 p[i].onclick = function(){ 
   alert("p is clicked and the id is " + this.id); 
 } 
}

Check out an example here for more clarity: http://jsbin.com/onaci/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...