问题
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?
回答1:
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/
回答2:
In your example you are using getElementsByTagName, which returns you an array of DOM elements, you could iterate that array and assign the onclick handler to each element, for example:
var clickHandler = function(){
alert('clicked!');
}
var elements = document.getElementsByTagName('div'); // All divs
for(var i = 0; i<elements.length; i++){
elements[i].onclick = clickHandler;
}
回答3:
it looks a little bit like you miss more than just the click function of jQuery. You also miss jquery's selector engine, chaining, and automatic iteration across collections of objects. With a bit more effort you can minimally reproduce some of those things as well.
var myClickCapture = function (selector) {
var method, name,iterator;
if(selector.substr(0,1) === "#") {
method = "getElementById";
name = selector.substr(1);
iterator = function(fn) { fn(document[method](name)); };
} else {
method = "getElementsByTagName";
name = selector;
iterator = function(fn) {
var i,c = document[method](name);
for(i=0;i<c.length;i++){
fn(c[i]);
};
};
myClickCapture.click = function (fn){
iterator(function(e){
e.onclick=fn;
})
}
return myClickCapture;
}
I haven't tested the code, but in theory, it gets you something like this:
myClickCapture("x").click(function(e){ alert("element clicked") });
Hopefully this gives you a sense of the sorts of things jquery is doing under the covers.
回答4:
document.getElementsByTagName("x")
returns an array of elements having the tagname 'x'.
You have to right event for each element in the returned array.
来源:https://stackoverflow.com/questions/1163073/pure-javascript-equivalent-of-jquery-click