[英]I have a form with select which creates elements. How I can do that elements creates only once?
I have JS code which creates paragraph and input elements according to html. 我有JS代码,可根据html创建段落和输入元素。 But I need this code to create each element only once.
但是我需要此代码仅创建一次每个元素。
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 HTML代码
<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>
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.