仅附加文本框一次

Append textbox only once

本文关键字:一次 文本      更新时间:2023-09-26

>我有一个带有在单击时附加文本框的功能的复选框。现在的问题是每次我单击复选框时都会出现一个新文本框,如果我单击复选框说 10 次,我会得到 10 个文本框。我想停止它,单击后我无法使用禁用文本框,因为在禁用文本框时有一个功能无法正常工作。对此的任何帮助将不胜感激。

<input onClick="myFunction();" id="demoteTask" name="demoteTask" type="checkbox"/>&nbsp;<label for"demoteTask_cbx">Demote to Child</label>
<span id="DemoteContainer"></span>
<script>
function myFunction() {
var span = document.createElement('SPAN');
span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
document.getElementById("DemoteContainer").appendChild(span);
}
</script>

我想实现这样的事情:

<script>
var tmp=1;
function myFunction() {
if(tmp%2==1)
{
var span = document.createElement('SPAN');
span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
document.getElementById("DemoteContainer").appendChild(span);
tmp++;
}
else
{
var d = document.getElementById("DemoteContainer");
var d_nested = document.getElementById("parent");
var throwawayNode = d.removeChild(d_nested);
tmp++;
}
}
</script>
您可以在

添加文本框之前检查元素(文本框)是否存在,如下所示:

function myFunction() {
    //check if text box with id "parent" exists, add if doesn't
    if( !document.getElementById("parent") ) {
        var span = document.createElement('SPAN');
        span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
        document.getElementById("DemoteContainer").appendChild(span);
    }
}

function myFunction() {
    //check if text box with id "parent" exists, add if doesn't
    if( !document.querySelector("#DemoteContainer input#parent") ) {
        var span = document.createElement('SPAN');
        span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
        document.getElementById("DemoteContainer").appendChild(span);
    }
}

脚本替换为以下脚本:-

<script>
function myFunction() {
    var elem = document.getElementById("parent");
    if(elem != null)
elem.parentNode.removeChild(elem);
var span = document.createElement('SPAN');
span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
document.getElementById("DemoteContainer").appendChild(span);
// document.getElementById("demoteTask").disabled = true;
}
</script>

如果您不介意每次单击文本框时再次生成文本框,请使用 innerHTML 替换容器的整个内容,而不是 appendChild:

document.getElementById("DemoteContainer").innerHTML = '<input id="parent" name = "parent" type="textbox" />';

<input onClick="myFunction();" id="demoteTask" name="demoteTask" type="checkbox"/>&nbsp;<label for"demoteTask_cbx">Demote to Child</label>
<span id="DemoteContainer"></span>
<script>
function myFunction() {
  var checkBox = document.getElementById('demoteTask');
  if (!checkBox.checked) {
    document.getElementById("parent").remove()
  } else {
    var span = document.createElement('span');
    span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
    document.getElementById("DemoteContainer").appendChild(span);
  }
}
  
  
  
</script>