2016-08-22 72 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>