我想使用 id 获取元素:
var a = document.getElementById("hello");
然后动态向其添加一个名为“labelText”的属性,并为其分配值“{labeltext}”。
我需要使用串联吗?
我尝试了以下方法,但没有成功:
document.getElementById("hello").setAttribute("labelText", "'{' + labelText + '}' ");
最佳答案
您正在做的事情基本上是有效的,Vohuman 首先明确识别的语法错误已得到纠正。
//Assign the Attribute:
var labelText='Some Value';
document.getElementById("hello").setAttribute('labelText', '{' + labelText + '}' );
//Define some variables for getting the results
var attributeEl = document.getElementById("attribute");
var theHTMLEl = document.getElementById("theHTML");
///Get the attribute value
var textLabelValue = document.getElementById("hello").getAttribute('labelText');
//Show the results:
attributeEl.textContent = textLabelValue;
theHTMLEl.textContent = document.getElementById("hello").outerHTML;
<div id="hello"></div>
The labelText attribute is:
<div id="attribute"></div>
The resulting HTML is:
<div id="theHTML"></div>
关于javascript - 如何使用 javascript 动态添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39069983/