javascript - Button.value 没有更改按钮的文本值

标签 javascript html object

我的 JavaScript 中有这段代码。它创建按钮并具有 onclick 功能,但 .value 不起作用

var button = document.createElement("button");
button.value = "+";
button.onclick = addBox;
document.getElementById("section").appendChild(button);

最佳答案

不是value但是textContent 。如果使用value,则需要使用<input type="button" />Button的文本位于 textContent .

为什么textContent而不是innerHTML ,因为textContent速度更快,它不会尝试解析为 html .

var button = document.createElement("button");
button.textContent = "+";
document.getElementById("section").appendChild(button);
<div id="section">
  
</div>

对于使用 type=button 输入

var button = document.createElement("input");
button.type = "button"
button.value = "+";
document.getElementById("section").appendChild(button);
<div id="section">
  
</div>

关于javascript - Button.value 没有更改按钮的文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42162120/

相关文章:

javascript - $(document).ready 在加载 DOM 之前触发

JavaScript 函数原型(prototype) : Object, 函数,还是两者?

java - Java 中的对象引用或值

javascript - 如何在 Javascript 中推送每个元素 2 个属性的数组?

javascript - 如何使用 jQuery/CoffeeScript 重定向到页面

javascript - 动态单击复选框并在列表中添加电子邮件地址并使用 JavaScript 删除重复的电子邮件地址

javascript - 如何在React Native FlatList中按 'something'排序?

javascript - 无法在 JQuery 中设置变量的 HTML

html - 将 Bootstrap 列居中

javascript - React 中的类变量与 ES6