簡體   English   中英

如何使用JavaScript動態添加屬性

[英]How to add an attribute dynamically using javascript

我想使用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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM