Javascript 如何将所有匹配元素视为一个集合?
有没有一种方法可以将包含同一类的元素转换、调整和处理为一个集合Javascript 如何将所有匹配元素视为一个集合?,javascript,dom,Javascript,Dom,有没有一种方法可以将包含同一类的元素转换、调整和处理为一个集合 <div class="f">fgfgh</div> <div class="f">dfg</div> <div class="f">qzer</div> <script> function _(c){ var x = document.getElementsByClassName(c); return x; }; _("f"
<div class="f">fgfgh</div>
<div class="f">dfg</div>
<div class="f">qzer</div>
<script>
function _(c){
var x = document.getElementsByClassName(c);
return x;
};
_("f")[all_of_them_not_0_1].innerHTML = "changed";
</script>
fgfgh
dfg
qzer
函数u(c){
var x=document.getElementsByClassName(c);
返回x;
};
_(“f”)[所有的都不是].innerHTML=“已更改”;
我当然可以循环使用它们,但这不是我想要的。这不是关于JavaScript,而是关于DOM API
不,DOM API中没有内置基于集合的变异操作(例如设置
innerHTML
)。您必须在元素之间循环(或者在幕后使用类似jQuery的东西)。这不是关于JavaScript,而是关于DOM API
不,DOM API中没有内置基于集合的变异操作(例如设置
innerHTML
)。您必须在元素之间循环(或者在幕后使用类似jQuery的工具)。您不能像class=“f changed”那样向元素添加类,然后使用css:
.f.changed:after {
content:'changed';
display:block;
/* any other stylings you need for this */
}
那么,当您想要切换文本时,您需要做的就是添加或删除类?不确定你有什么反对循环的方法,但这是一种方法。你能不能像class=“f changed”那样添加一个类,然后使用css:
.f.changed:after {
content:'changed';
display:block;
/* any other stylings you need for this */
}
那么,当您想要切换文本时,您需要做的就是添加或删除类?不确定您反对循环的原因,但这是一种方法。一个想法是将
元素.prototype
方法添加到HTMLCollection.prototype
。但是,请注意
var elementMethods = Object.getOwnPropertyNames(Element.prototype);
elementMethods.forEach(attachElementMethodsToHTMLCollection);
function attachElementMethodsToHTMLCollection(methodName) {
HTMLCollection.prototype[methodName] = function() {
var result = [];
for (var i = 0; i < this.length; i++) {
if (methodName !== 'innerHTML' && typeof Element.prototype[methodName] === 'function') {
result.push(Element.prototype[methodName].apply(this.item(i), arguments))
} else {
result.push(arguments.length ? this.item(i)[methodName] = arguments[0] : this.item(i)[methodName])
}
}
return result;
};
};
演示:一个想法是将
元素.prototype
方法添加到HTMLCollection.prototype
。但是,请注意
var elementMethods = Object.getOwnPropertyNames(Element.prototype);
elementMethods.forEach(attachElementMethodsToHTMLCollection);
function attachElementMethodsToHTMLCollection(methodName) {
HTMLCollection.prototype[methodName] = function() {
var result = [];
for (var i = 0; i < this.length; i++) {
if (methodName !== 'innerHTML' && typeof Element.prototype[methodName] === 'function') {
result.push(Element.prototype[methodName].apply(this.item(i), arguments))
} else {
result.push(arguments.length ? this.item(i)[methodName] = arguments[0] : this.item(i)[methodName])
}
}
return result;
};
};
演示:为什么要将循环抛出窗口,它们存在的原因是您应该查看jQuery。它的函数语法非常匹配。
document.querySelector('.f')代码>,然后循环。或者document.querySelectorAll()。请查看此解决方案,并告诉我它是否满足您的需要。为什么要将循环抛出窗口,它们的存在是有原因的,您应该查看jQuery。它的函数语法非常匹配。document.querySelector('.f')代码>,然后循环。或document.querySelectorAll()。请查看此解决方案,并告诉我它是否满足您的需要。