我有一个带有select的表单,它创建了元素。我怎么能做这个元素只创造一次?

时间:2021-01-11 07:33:42

I have JS code which creates paragraph and input elements according to html. But I need this code to create each element only once.

我有JS代码,根据html创建段落和输入元素。但我需要这个代码只创建一次元素。

Peace of Javascript code

和平的Javascript代码

function comFunction(sel) {
   switch (sel.value) {
        case 'skype':
            var skype = document.createElement("P");
            var temp = document.createTextNode("Enter your skype");
            var input = document.createElement("input");
            input.type = "text";
            skype.appendChild(temp);
            form.appendChild(skype);
            form.appendChild(input);
            break;
}

HTML code

<form id="form">
<select name="liason" id="liason" onchange="comFunction(this);">
    <option value="skype">Skype</option>
    <option value="icq">ICQ</option>
    <option value="facebook">Facebook</option>
    <option value="email">e-mail</option>
</select>
</form>

1 个解决方案

#1


0  

If you add an id to the elements being created and appended to the DOM, you can then check for their existence before running the code that would create them a second time:

如果向正在创建的元素添加id并将其附加到DOM,则可以在运行第二次创建它们的代码之前检查它们是否存在:

 function comFunction(sel) {

   switch (sel.value) {
    case 'skype':
        if(document.getElementById("skypeParagraph") === null) {
           var skype = document.createElement("P");
           skype.setAttribute("id", "skypeParagraph");
           var temp = document.createTextNode("Enter your skype");
           var input = document.createElement("input");
           input.type = "text";
           skype.appendChild(temp);
           form.appendChild(skype);
           form.appendChild(input);
        }
        break;
 }

#1


0  

If you add an id to the elements being created and appended to the DOM, you can then check for their existence before running the code that would create them a second time:

如果向正在创建的元素添加id并将其附加到DOM,则可以在运行第二次创建它们的代码之前检查它们是否存在:

 function comFunction(sel) {

   switch (sel.value) {
    case 'skype':
        if(document.getElementById("skypeParagraph") === null) {
           var skype = document.createElement("P");
           skype.setAttribute("id", "skypeParagraph");
           var temp = document.createTextNode("Enter your skype");
           var input = document.createElement("input");
           input.type = "text";
           skype.appendChild(temp);
           form.appendChild(skype);
           form.appendChild(input);
        }
        break;
 }