我必须通过匹配条件来创建元素。但是当我执行另一个条件时,先前创建的元素就在那里。如何使用Java脚本避免这种重复? 我有这样的Javascript函数:
function maketext(p) {
var f = document.createElement('form');
f.setAttribute('method', "post");
f.setAttribute('id', "update");
f.setAttribute('action', "updateprod");
if (p == "Code") {
var inp = document.createElement('input');
inp.setAttribute("placeholder", "Type Here");
inp.setAttribute("class", "form-control");
inp.setAttribute("id", "mcode");
inp.setAttribute("name", "mcode");
var sub = document.createElement("input");
sub.setAttribute("type", "submit");
sub.setAttribute("value", "submit");
sub.setAttribute("class", "btn btn-primary");
f.appendChild(inp);
f.appendChild(sub);
document.getElementById("mys").appendChild(f);
}
if (p == "Name") {
var inp = document.createElement('input');
inp.setAttribute("placeholder", "Type Here");
inp.setAttribute("class", "form-control");
inp.setAttribute("id", "mname");
inp.setAttribute("name", "mname");
var sub = document.createElement("input");
sub.setAttribute("type", "submit");
sub.setAttribute("value", "submit");
sub.setAttribute("class", "btn btn-primary");
f.appendChild(inp);
f.appendChild(sub);
document.getElementById("mys").appendChild(f);
}
}
HTML
<a href="#" onclick="maketext('Code')" data-toggle="modal" data-target="#myModal" class="btn btn-info btn-lg">Edit</a>
<a href="#" onclick="maketext('Name')" data-toggle="modal" data-target="#myModal" class="btn btn-info btn-lg">Edit</a>
答案 0 :(得分:1)
在创建元素之前,请从div
function maketext(p) {
document.getElementById("mys").innerHTML = ''
// rest of the code
}