javascript - jQuery 将属性集作为字符串插入到标签中

标签 javascript jquery attributes

我有包含一组属性的变量 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/

相关文章:

python - 属性错误: module 'pandas.io.sql' has no attribute 'frame_query'

c# - 反射(reflect)属性以获取属性。当它们在别处定义时怎么办?

javascript - 在带有 Angular 的 NativeScript 中,如何获取接口(interface)元素的 id?

javascript - open layers 3 如何以编程方式绘制多边形?

javascript - 将一个值分解为两个幂的结果

javascript - 在初始化之前设置延迟或超时

jquery - 锁定横向设备方向

javascript - 使用下划线继承

javascript - 如何使 Bootstrap 模式宽度适应包含的图像

python - Python 中 int 实例的 int 值存储在哪里?