1

我有 5 个相同类的 div,但不同的 id 堆叠在一起。如何使用 javascript 遍历它们?它们被命名为 div1、div2、div3 等...

另外,如何在遍历时更改每个 div 的属性?

非常感谢你。

谭。

4

7 回答 7

4

在现代浏览器中,您可以使用getElementsByClassName函数获取它们:

var elements = document.getElementsByClassName('myClass');

for (var i = 0, n = elements.length; i < n; i++) {
  //..
}

请注意,我elements.length只得到一次,这是迭代 HTMLCollections 时的常见做法。

那是因为这些集合是“实时的”,它们可以随时更改,并且在每次迭代时访问 length 属性是昂贵的。

有关完整的跨浏览器实现,请查看 Resig 先生的这篇文章:

编辑:我给你留下了Dustin Diaz getElementsByClassName 跨浏览器纯 DOM 实现的重构版本:

function getElementsByClassName(node,classname) {
  if (node.getElementsByClassName) { // use native implementation if available
    return node.getElementsByClassName(classname);
  } else {
    return (function getElementsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("*"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    })(classname, node);
  }
}
于 2009-09-16T06:12:49.303 回答
2
for(var i = 1; i++; i<=5){
    var div = document.getElementById("div" + i);
    //do stuff with div
}

编辑:我看到你称之为“命名” div1...div5,你必须给它 id="div1" 也让它工作

于 2009-09-16T06:12:10.147 回答
1

首先阅读这篇文章

getElementsByClassName 速度比较

增强的 getElementsByClassName

var elements = document.getElementsByTagName("div");

for ( var i = 0; len = elements.length; i < len; i ++ )
{
    if ( elements[i].className === "yourclassname" )
    {
        // change the desired attribute of element.
        //Eg elements[i].style.display = "none";
    }
}

使用 jQuery每个函数

$(".yourclassname").each ( function() {
    // $(this) will fetch the current element
});
于 2009-09-16T06:11:48.680 回答
1

你在使用原型或 jQuery 之类的东西吗?如果是这样,我强烈推荐其中之一,因为它们使遍历变得非常容易。例如,使用 Prototype 将是:

$$('.className').each(function(s) {
    //what you want to do
});
于 2009-09-16T06:13:35.417 回答
1

基于库的答案是显而易见的,但如果您被限制使用它们,这里有一些方法比使用 Firefox 的(新的和光荣的!)更兼容document.getElementsByClassName

于 2009-09-16T06:24:56.393 回答
1

破解它需要做一些工作,但这里有一篇关于如何在旧浏览器中启用 queryselectorAll 的文章:

http://ajaxian.com/archives/creating-a-queryselector-for-ie-that-runs-at-native-speed

在 Mootools 或 Prototype 中执行此操作:

 $$('.className').each(function(element, index) {
   //what you want to do
 });

在 Jquery 中,没有双美元(正如其他人发布的那样)是一样的:

 $('.className').each(function() {
   //what you want to do
 });
于 2009-09-16T06:58:19.740 回答
0

这是一个jQuery解决方案:

设置所有div的属性:

$(".yourclassname").attr("attribute","value");

设置所有div的文本内容:

$(".yourclassname").text("New content");

设置所有div的html内容:

$(".yourclassname").html("<h1>New content</h1><p>blah blah blah</p>");

可以在http://jquery.com/找到 jQuery 库。

于 2009-09-16T06:30:51.217 回答