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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:01:38  来源:igfitidea点击:

Setting button text via javascript

javascripthtmlwindows-store-apps

提问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>

Demo:http://jsfiddle.net/CuXHm/

演示:http : //jsfiddle.net/CuXHm/

回答by Denys Séguret

The value of a buttonelement isn't the displayed text, contrary to what happens to inputelements of type button.

a的值按钮元素是不显示的文本,相反会发生什么input类型的按钮元素。

You can do this :

你可以这样做 :

 b.appendChild(document.createTextNode('test value'));

Demonstration

示范

回答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);

http://jsfiddle.net/jUVpE/

http://jsfiddle.net/jUVpE/