首页 > 解决方案 > 使用循环或在新构造函数内部进行 DOM 操作?

问题描述

我有几个<div>withdata-bg-color属性。我创建了一个函数,让所有这些都使用querySelectorAll并根据data-bg-color. 我对 JS 的构造方法很陌生,所以我的问题是:操作这些元素的更好方法是什么?

有两种选择:

一种是一次获取所有元素并在构造函数中遍历它们:

var Background = function (selector) {
    this.elements = (selector) ? document.querySelectorAll(selector) : document.querySelectorAll("[data-bg-color]");
    if(this.elements.length) this.setColor();
};

Background.prototype.setColor = function () {
    Array.from(this.elements, function (element) {
        element.style.backgroundColor = element.getAttribute("data-bg-color");
    });
};

var bg = new Background();

二,是在循环中为每个 data-bg-color 元素创建新的构造函数:

var Background = function (element) {
    this.element = element;
    this.setColor();
};

Background.prototype.setColor = function () {
    this.element.style.backgroundColor = this.element.getAttribute("data-bg-color");
};

for( var i=0; i<document.querySelectorAll("[data-bg-color]").length; i++ ){
    new Background( document.querySelectorAll("[data-bg-color]")[i] );
}

在第一种情况下,我只想简单地处理这个过程,所以只new Background()需要。它会自动获取data-bg-color页面上的所有元素并为它们设置颜色。此外,如果用户只想定位所需的元素,他可以使用new Background("#modal [data-bg-color]").

这是一个辅助函数,所以原型方法可能不适合这个,但如果它变得更大,我想避免意大利面条代码。

标签: javascriptprototype

解决方案


似乎(至少从第二个版本开始)Background一旦构造了实例,您就没有使用实例了。不使用返回的值new Background(并最终被垃圾收集),因此甚至为此任务定义构造函数似乎有点过头了。

当您需要保持状态并需要可以稍后在该状态上调用的方法时,构造函数更适合。

但是,在这种情况下,我会坚持使用一个简单的功能来完成这项工作:

function applyBackground(selector = "[data-bg-color]") {
    Array.from(document.querySelectorAll(selector), 
               elem => elem.style.backgroundColor = elem.getAttribute("data-bg-color"));
}

还要注意参数的默认值的使用。这里使用箭头函数值得商榷。我只是提供它作为替代。


推荐阅读