繁体   English   中英

为一个元素设置多个属性

[英]Setting multiple attributes for an element

我试图一次为一个元素设置多个属性。 我找到了这个答案 ,并对这个答案发表了评论 在JSFiddle中,他不使用字符串作为属性名称,这与使用字符串的答案相反。

注释中的JSFiddle问题在于,它无法编辑元素的文本。 我尝试添加该功能,但是没有用。

我在第7行添加了以下内容:

else if (at[prop] === html) {
    this.innerHTML = set[idx];
}

但我收到以下错误:

未捕获的ReferenceError:未定义html

如何在注释后的JSFiddle中添加更改文本的功能?

回答JSFiddle

评论JSFiddle (编辑)

在比较中使用'html' 同时通过this背景下recursiveSet功能是指thisdiv元素。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM