gpt4 book ai didi

javascript - JSON 到 setAttribute()

转载 作者:行者123 更新时间:2023-11-30 13:28:33 25 4
gpt4 key购买 nike

我几乎完成了以下工作,但遇到了许多令人困惑的方法。希望在 setAttribute() 方法属性的 attr{} 中使用键:值,而无需框架。

请借一个 slim 的解决方案:

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" });

关于javascript - JSON 到 setAttribute(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7620963/

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