javascript - 如何使用 javascript 动态添加属性

标签 javascript jquery string dom attributes

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

相关文章:

javascript - 具有属性的深层复制 Javascript 数组

jquery - 固定 float div 滚动

ruby - 如何获取字符串中可用键的所有组合

javascript - setTimeout 在 Angular 5 中不起作用

javascript - HighCharts:在 maincontentText 中使用匿名函数

javascript - 覆盖、取消或使预渲染页面失效

jquery - IE11 的 CORS 请求

javascript - jquery,为什么 .data() 在 Internet Explorer 中不起作用?

c++ - 使用函数更改 std::string 的内容

c - 如何让 fgets() 在开头忽略 a\n?