Html 通过javascript设置按钮文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16303954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting button text via javascript
提问by dinnouti
I am setting up a button via javascript, but the button shows not the text.
我正在通过 javascript 设置一个按钮,但该按钮不显示文本。
Any recommendation on how to fix it?
关于如何修复它的任何建议?
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);
Thanks!
谢谢!
回答by Stevie
Basically, use innerHTML instead of value, because the 'button' type you are appending sets it's value in its innerHTML.
基本上,使用innerHTML 而不是值,因为您附加的'button' 类型在其innerHTML 中设置它的值。
JS:
JS:
var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'test value';
var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);
Looks like this in the DOM:
在 DOM 中看起来像这样:
<div id="divWrapper">
<button content="test content" class="btn">test value</button>
</div>
回答by Denys Séguret
回答by Rick Viscomi
Create a text node and append it to the button element:
创建一个文本节点并将其附加到按钮元素:
var t = document.createTextNode("test content");
b.appendChild(t);
回答by cgatian
Set the text of the button by setting the innerHTML
通过设置innerHTML来设置按钮的文本
var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'test value';
var wrapper = document.getElementById('divWrapper');
wrapper.appendChild(b);