JavaScript 脚本只创建一个文本区域而不是 4 个

JavaScript script create only one textarea instead of 4

    <div id="textfelder"></div>
<script>
if (!document.getElementById('command1')) {
    string = '<input type="text" id="command1">';
    document.getElementById("textfelder").innerHTML = string;
    }
if (!document.getElementById('command2')) {
    string = '<input type="text" id="command2">';
    document.getElementById("textfelder").innerHTML = string;
    }
if (!document.getElementById('command3')) {
     string = '<input type="text" id="command3">';
     document.getElementById("textfelder").innerHTML = string;
    }
if (!document.getElementById('command4')) {
     string = '<input type="text" id="command4">';
     document.getElementById("textfelder").innerHTML = string;
    }
</script>

这只会创建一个 ID 为 "command4" 的文本区域。 当我删除最后一个 if 语句时,脚本将创建 ID 为 "command3" 的文本区域,但不会创建其他文本区域。 谢谢! :D

如果您不使用 jquery,您应该使用 +=

document.getElementById("textfelder").innerHTML += string;

希望对您有所帮助。

使用 += 运算符代替 =

    <div id="textfelder"></div>
<script>
if (!document.getElementById('command1')) {
    string = '<input type="text" id="command1">';
    document.getElementById("textfelder").innerHTML += string;
    }
if (!document.getElementById('command2')) {
    string = '<input type="text" id="command2">';
    document.getElementById("textfelder").innerHTML += string;
    }
if (!document.getElementById('command3')) {
     string = '<input type="text" id="command3">';
     document.getElementById("textfelder").innerHTML += string;
    }
if (!document.getElementById('command4')) {
     string = '<input type="text" id="command4">';
     document.getElementById("textfelder").innerHTML += string;
    }
</script>

根据您的代码。它覆盖了 textfielder 中的内容。尝试使用下面的代码附加它。

document.getElementById("textfelder").innerHTML += string;