[英]Setting multiple attributes for an element
我試圖一次為一個元素設置多個屬性。 我找到了這個答案 ,並對這個答案發表了評論 。 在JSFiddle中,他不使用字符串作為屬性名稱,這與使用字符串的答案相反。
注釋中的JSFiddle問題在於,它無法編輯元素的文本。 我嘗試添加該功能,但是沒有用。
我在第7行添加了以下內容:
else if (at[prop] === html) {
this.innerHTML = set[idx];
}
但我收到以下錯誤:
未捕獲的ReferenceError:未定義html
如何在注釋后的JSFiddle中添加更改文本的功能?
評論JSFiddle (編輯)
在比較中使用
'html'
。 同時通過this
背景下recursiveSet
功能是指this
對div
元素。this
總是指我們正在執行的函數的“所有者”。 如果沒有所有者 ,它將引用window
。
嘗試這個:
var manipulateAttributes = function(attr, element) { var recursiveSet = function(at, set) { for (var prop in at) { /* check if object and not a dom node or array */ if (typeof at[prop] == 'object' && at[prop].dataset == null && at[prop][0] == null) { recursiveSet(at[prop], set [prop]); } else if (prop == 'html') { this.innerHTML = at[prop]; } else { set [prop] = at[prop]; } } }.bind(element); recursiveSet(attr, element); } var test = document.getElementById("test"); manipulateAttributes({ html: 'hellop', style: { background: "lightGreen", color: "blue", width: "100px" }, className: "testclass", onclick: function(e) { alert("the test div has been clicked and its width is: " + this.style.width); } }, test);
.testclass { font-size: 32px; font-weight: bold; cursor: pointer; }
<div id="test" style="width:200px;height:200px;background:#000;color:#fff;">Test</div>
else if (at[prop] === html) {
如下替換上面的代碼行進入循環
else if (at[prop] === 'hellop') {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.