基本上我喜歡用同一個類名向多個元素添加一個新類。目前它只爲最後一個類添加一個類。我曾嘗試使用document.querySelectorAll但沒有結果。我錯過了什麼?如何將一個類添加到多個元素?
HTML示例
<div class="model"></div>
<div class="model"></div>
<div class="model"></div>
JS
_updateParagraph: function(settings, className) {
var paragraph = document.querySelector('.' + className);
paragraph.className = className;
this._updateParagraphClasslist(settings, paragraph);
},
FULL JS
App.Views.Preview = Backbone.View.extend({
el: "#preview",
initialize: function() {
this.listenTo(this.model, "change", this.update);
},
update: function() {
var
layout = [this.model.get("model")],
format = [this.model.get("size"), this.model.get("color-outside"), this.model.get("color")],
color = [this.model.get("color-inside")],
material = [this.model.get('material')],
lamination = [this.model.get('lamination')],
logo = [this.model.get('embossing')];
this._updateParagraph(layout, 'layout');
this._updateParagraph(format, 'front');
this._updateParagraph(format, 'back');
this._updateParagraph(lamination, 'kit-front');
this._updateParagraph(lamination, 'kit-back');
this._updateParagraph(logo, 'embossing');
this._updateParagraph(color, 'colorinner');
this._updateParagraph(color, 'model');
},
_updateParagraph: function(settings, className) {
var paragraph = document.querySelector('.' + className);
paragraph.className = className;
this._updateParagraphClasslist(settings, paragraph);
},
_updateParagraphClasslist: function(settings, paragraph) {
_.each(settings, function(setting) {
if (_.has(setting, "visual")) {
paragraph.classList.add(setting.visual);
}
});
}
});
使用'addclass'。 –
爲什麼原生js DOM函數和'jQuery'標籤? ^^ – moonwave99
@AmeyDeshpande http://jsfiddle.net/infous/8woaegx2/這可能是你想要的代碼的一個明確的例子。檢查DOM中的結果。 – starikovs