我正在通过 JavaScript 设置一个按钮,但该按钮不显示文本。
关于如何修复它有什么建议吗?
var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.value = 'test value';
var wrapper = document.getElementById(divWrapper);
wrapper.appendChild(b);
使用 textContent
而不是 value
来设置按钮文本。
通常,值属性用于在按钮作为表单数据提交时将值与按钮相关联。
请注意,虽然可以使用 innerHTML
设置按钮文本,但应首选使用 textContext
,因为它的性能更高,并且可以防止跨站点脚本攻击,因为它值未解析为 HTML。
JS:
var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.textContent = 'test value';
var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);
在 DOM 中生成:
<div id="divWrapper">
<button content="test content" class="btn">test value</button>
</div>
演示: https://jsfiddle.net/13ucp6ob/