JSON to setAttribute()
JSON to setAttribute()
我几乎得到了以下工作,但遇到了许多令人困惑的方法。我们希望在setAttribute()方法属性的attr{}中使用key:value,而不需要框架。
请提供一个简单的解决方案:
testDiv = document.getElementById("testDiv");
attr = {
align:"center",
title:"The Test Div"
};
//Possible converting JSON to String, the use in setAttribute?
for(var x in attr) alert(x + " , " + attr[ x ] );
testDiv.setAttribute( x , attr[ x ]);
这里没有JSON,只有对象文字。不管怎样,如果我理解正确的话您想为一个特定元素设置所有指定的属性?如果你想要一些可重用的东西,函数中的循环应该很容易做到:
function setMultipleAttributes(el, attributes) {
for (var attr in attributes)
el.setAttribute(attr, attributes[attr]);
}
var testDiv = document.getElementById("testDiv");
setMultipleAttributes(testDiv, { align : "center", title : "The Test Div" });
您的问题与" JSON "(实际上只是一个JavaScript对象文字)或设置属性无关。它是这样的:
for(var x in attr) alert(x + " , " + attr[ x ] );
testDiv.setAttribute( x , attr[ x ]);
由于在for
循环中没有使用大括号,因此只执行紧跟其后的语句。如果我添加大括号,上面的代码看起来像这样:
for(var x in attr){
alert(x + " , " + attr[x] );
}
testDiv.setAttribute( x , attr[x]);
setAttribute
在循环中不被调用-它只是在结束时被调用一次。相反,您可能希望…
for(var x in attr){
alert(x + " , " + attr[x] );
testDiv.setAttribute( x , attr[x]);
}
相关文章:
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- jQuery AJAX write to XML
- grep in JQuery to C#
- how to convert html <div> to pdf
- Node.js - POST to iFrame?
- SVG xml to image
- Advantages to DOMParser vs template & innerHTML
- how to split a string with ','
- How to declare a Map containing certain properties with flow
- Javascript setattribute-名称和值无效
- Php variable obj to js
- 如何在submit to sightly时将表单输入值作为参数传递给WCMUsePojo
- D3JS selectAll to append rect
- Javascript connect to websocket
- Underscore each to update collection
- 在哪里可以找到R-to-JavaScript编译器
- SCEditor BBcode to HTML parsing
- Javascript RegEx to XML Schema RegEx
- setattribute to addEventListener
- JSON to setAttribute()