0

做类似的事情的替代方法是什么

$(".myElement").each(function(){ 
    //function
});

用纯Javascript?

4

5 回答 5

6

这将迭代div当前文档中的所有 s。你可以替换etc. 并用他们的anddocument.getElementsByClassName('someclass')做一些事情attributesvalues

var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
    doSomething(elements[i]);
}

这是jsfiddle:http: //jsfiddle.net/allenski/p7w5btLa/

于 2013-08-11T09:03:41.787 回答
3
$(#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
  }
于 2013-08-11T08:58:24.680 回答
0
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.

于 2013-08-11T08:58:17.243 回答
0

每个函数的替代方法,这里有两个:

设置

var $all = $('*');
var len = $all.length;

1

while(--len){
   // use $($all[len]); for jQuery obj
   var elem = $all[len];
   doWork(elem);
}

2

//reset len for next loop
len = $all.length;
do {
   var $elem = $all.filter(':eq('+ --len + ')');
   doWork($elem);
} while (len);
于 2013-08-11T09:17:26.157 回答
-1

You have to use a for loop. look at http://www.w3schools.com/js/js_loop_for.asp

于 2013-08-11T08:57:58.367 回答