简体   繁体   English

为一个元素设置多个属性

[英]Setting multiple attributes for an element

I'm trying to set multiple attributes to an element at one shot. 我试图一次为一个元素设置多个属性。 I found this answer , and this comment to that answer. 我找到了这个答案 ,并对这个答案发表了评论 In the JSFiddle there, he doesn't use a string for the property name, as opposed to the answer which uses a string. 在JSFiddle中,他不使用字符串作为属性名称,这与使用字符串的答案相反。

The problem with the JSFiddle in the comment, is that it doesn't have the ability to edit the text for the element. 注释中的JSFiddle问题在于,它无法编辑元素的文本。 I tried adding that capability, but it didn't work. 我尝试添加该功能,但是没有用。

I added the following at line 7: 我在第7行添加了以下内容:

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

But I got the following error: 但我收到以下错误:

Uncaught ReferenceError: html is not defined 未捕获的ReferenceError:未定义html

How can I add the functionality of changing the text to the commented JSFiddle? 如何在注释后的JSFiddle中添加更改文本的功能?

Code

Answer JSFiddle 回答JSFiddle

Comment JSFiddle (edited) 评论JSFiddle (编辑)

Use 'html' in your comparison. 在比较中使用'html' Also pass this context in recursiveSet function to refer this to div element. 同时通过this背景下recursiveSet功能是指thisdiv元素。 this always refers to the “owner” of the function we're executing. this总是指我们正在执行的函数的“所有者”。 If there is no owner , it will refer to the window .. 如果没有所有者 ,它将引用window

Try this: 尝试这个:

 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