我有包含一组属性的变量 x。
var x = 'class="test test1 test2" id="xyz" style="color:red"';
如何将 x 插入 <body>
标签。所以 body 看起来像
<body class="test test1 test2" id="xyz" style="color:red">
最佳答案
您可以创建一个 temp 元素并为其添加 att 属性,然后将其所有属性附加到正文:
var x = 'class="test test1 test2" id="xyz" style="color:red"',
temp = $("<b "+x+">")[0],
attr = {};
for (var i=0, attrs=temp.attributes, l=attrs.length; i<l; i++){
attr[attrs.item(i).nodeName] = attrs.item(i).value;
}
$("body").attr(attr);
演示:http://jsbin.com/udilib/edit#javascript,html,live
但是如果您可以将类、id 和样式作为对象而不是字符串,将为您节省一些代码。
关于javascript - jQuery 将属性集作为字符串插入到标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7407905/