我写的html代码如下
<input type="text" class="inputstyle" id="text" name="text">
这是JS代码
function addtolist() {
//get input
var textappend = document.getElementById("text").innerHTML;
console.log(textappend);
console.log(typeof (textappend));
console.log(choice)
if (textappend != "") {
choice.push(textappend); // append text to choice
}
document.getElementById("list").innerHTML = choice; // output list
}
如果点击按钮,则生成按钮。按钮将调用addtolist()
函数,该函数将添加id="text"(类型字符串)到选择(分支数组)。我试着输入text "Hello World"对于<input>
和addtolist()
函数,它是附加空白字符串的选择。我不知道为什么帮我解决这个问题。(对不起,我的语法,我不懂英语)
要获取<input type="text"
元素的值,请使用.value
而不是.innerHTML
。
var textappend = document.getElementById("text").value;
所以假设你在HTML中有一个h1,包含你想要使用的文本,你可以使用.value
而不是.innerhtml
,我建议你使用它,因为你的项目越来越大,使用.innerhtml
可能会变得复杂,所以使用.value
代替。
function addtolist() {
//get input
var textappend = document.getElementById("text").value;
console.log(textappend);
console.log(typeof (textappend));
console.log(choice)
if (textappend != "") {
choice.push(textappend); // append text to choice
}
document.getElementById("list").innerHTML = choice; // output list
}
希望它能帮助你!