做类似的事情的替代方法是什么
$(".myElement").each(function(){
//function
});
用纯Javascript?
这将迭代div
当前文档中的所有 s。你可以替换etc. 并用他们的anddocument.getElementsByClassName('someclass')
做一些事情attributes
values
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
doSomething(elements[i]);
}
这是jsfiddle:http: //jsfiddle.net/allenski/p7w5btLa/
$(#myElement)
You are trying to iterate over a id
selector. ID has to be unique in a HTML page.
If it's a class or element
tags you want to iterate over you can use a for
loop.
var $elems = $('.someClass');
for(var i=0; i< $elems.length; i++ ) {
// $elems[i] --> Gives you a `DOM` element
// $elems.eq(i) --> Gives you a `jQuery` object
}
Vanilla Javascript
var elems = document.getElementsByClassName('someClass');
for(var i=0;i< elems.length;i ++) {
elem[i] // Based on index
}
getElementsByTagName
if you want to iterate over specific tags.
getElementsByName
- get the elements based on name attribute.
You can also use document.querySelectorAll
to get a list of objects and iterate over them.
var elems = document.querySelectorAll('.someClass')
for(var i=0; i<elems.length; i++) {
elems[i] // Give you DOM object
}
var el = $(something);
for (var i = 0; i < el.length; i++) {
// do something with el[i] or more often with $(el[i])
}
el
is a pseudo-array (or array-like Object) that has a length
and elements accessible with the []
operator in the range 0...length-1
. So you can do el[0]
, el[1]
etc., but remember that el
elements aren't jquery "objects", normally they are DOM elements, so you can't do el[0].text("Hello")
. As in the each
method, you have to do $(el[0]).text("Hello");
It's even wrong to do:
for (var i = 0; i < $(something).length; i++) {
// do something with el[i] or more often with $(el[i])
}
because in this way the $(something)
will be recalculated every cycle.
每个函数的替代方法,这里有两个:
var $all = $('*');
var len = $all.length;
while(--len){
// use $($all[len]); for jQuery obj
var elem = $all[len];
doWork(elem);
}
//reset len for next loop
len = $all.length;
do {
var $elem = $all.filter(':eq('+ --len + ')');
doWork($elem);
} while (len);
You have to use a for loop. look at http://www.w3schools.com/js/js_loop_for.asp