【发布时间】:2013-08-27 01:04:10
【问题描述】:
我有许多带有 publish_0 类的 div,我想通过单击按钮将其更改为 publish_1。
现在我用这个,但它只改变一个项目。
如何将 setattribute 应用于所有具有 publish_0 的项目。
document.querySelector('.publish_0').setAttribute("class", "publish_1");
【问题讨论】:
我有许多带有 publish_0 类的 div,我想通过单击按钮将其更改为 publish_1。
现在我用这个,但它只改变一个项目。
如何将 setattribute 应用于所有具有 publish_0 的项目。
document.querySelector('.publish_0').setAttribute("class", "publish_1");
【问题讨论】:
您需要使用循环来遍历所有元素并单独设置它们的类属性值:
var els = document.querySelectorAll('.publish_0');
for (var i=0; i < els.length; i++) {
els[i].setAttribute("class", "publish_1");
}
【讨论】:
getElementsByClassname 而不是querySelectorAll,它的性能要好得多。查看示例here
当你不能使用 jQuery 但想要类似的便利时,你可以执行以下操作。将以下代码添加到文件顶部或其他容易看到的地方。
NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;
现在您可以在您的代码中执行此操作:
document.querySelectorAll('body,main,article,[class*=content],[class*=center]')
.forEach((function(x){ x.setAttribute("style","width:1920px");}))
或者更好的是,如果浏览器支持 ECMAScript2015,你可以使用箭头语法:
document.querySelectorAll('[class*=content]')
.forEach( x=> x.setAttribute("style","width:1200px"))
如果您愿意,可以将语句全部放在一行中。
【讨论】:
你可以在 jquery 中使用它:
$(".publish_0").attr("class", "publish_1")
或者,使用 getElementsByClassName 并遍历返回的 DOM 元素。
【讨论】: