2016-08-22 78 views
0

我想用id来获取元素:如何添加属性使用JavaScript动态

var a = document.getElementById("hello"); 

,然后动态地添加属性给它称为“LabelText的”,并指定值“{LabelText的}”来了。

我需要使用串联吗?

我尝试以下,但它没有工作:

document.getElementById("hello").setAttribute("labelText", "'{' + labelText + '}' "); 
+0

你的报价是错误的。 – SLaks

+0

可以请给更多的解释 – sarah

+0

@SLaks在哪里?您可以请您更正代码声明 – sarah

回答

1

你在做什么工作基本上与第一明确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>