gpt4 book ai didi

javascript - 如何在一个变量中获取body标签的所有类和样式属性

转载 作者:行者123 更新时间:2023-11-28 12:07:43 27 4
gpt4 key购买 nike

我有以下内容

<body class="test test1 test2" style="color:red; font-size:12px">...</body>

使用 jQuery,我如何将 body 标记的所有属性存储在变量 x 中。换句话说,我想要

var x = 'class="test test1 test2"style="color:red; font-size:12px"';

最佳答案

您可以使用element.attributes
像这样:

var body = document.body,  
attries = body.attributes,
arr = [];
for(var i=0, len=attries.length; i<len; i++){
var attr = attries[i];
arr.push(attr.nodeName + '="' + attr.nodeValue + '"');
}
var x = arr.join(" ");
alert(x);

看这里:http://jsbin.com/ihiwod

更新:

但是,在 IE(<=7) 中,上面的代码会生成比您想要的更多的属性,因为未设置的属性也会添加到这些浏览器中的 element.attributes 中。

改进后的代码为:

var body = document.body,  
attries = body.attributes,
arr = [];
for(var i=0, len=attries.length; i<len; i++){
var attr = attries[i];
if(attr.specified){
var attr_name = attr.nodeName,
attr_val = attr_name === "style" ? body.style.cssText
: attr.nodeValue;
arr.push(attr_name + '="' + attr_val + '"');
}
}
var x = arr.join(" ");
alert(x);

关于javascript - 如何在一个变量中获取body标签的所有类和样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7398532/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com