javascript - 使用循环或在新构造函数内部进行 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]")
.
这是一个辅助函数,所以原型方法可能不适合这个,但如果它变得更大,我想避免意大利面条代码。
解决方案
似乎(至少从第二个版本开始)Background
一旦构造了实例,您就没有使用实例了。不使用返回的值new Background
(并最终被垃圾收集),因此甚至为此任务定义构造函数似乎有点过头了。
当您需要保持状态并需要可以稍后在该状态上调用的方法时,构造函数更适合。
但是,在这种情况下,我会坚持使用一个简单的功能来完成这项工作:
function applyBackground(selector = "[data-bg-color]") {
Array.from(document.querySelectorAll(selector),
elem => elem.style.backgroundColor = elem.getAttribute("data-bg-color"));
}
还要注意参数的默认值的使用。这里使用箭头函数值得商榷。我只是提供它作为替代。
推荐阅读
- swift - 为什么将结构转换为 AnyObject 而不是 swift 中的编译错误?
- video - H264 P&B 帧是否包含像素值?
- android - 将数据从活动传递到片段android工作室
- compass-sass - gem install compass - 无法构建 gem 本机扩展
- python - PyCharm 中的“Feather”库安装失败
- julia - 为什么 Julia 变量不存在于 for 循环的范围内?
- c++ - 使用指针将像素强度分配给未初始化的 Mat 矩阵
- c++ - 如何让我的函数在 if 语句中返回到程序中的特定点?
- java - ReadableMap 中的键数?
- function - 有没有办法通过函数传递/选择输出?