Remove Dynamic Element With Javascript [closed]

做~自己de王妃 提交于 2020-06-16 03:30:11

问题


I make a form with dynamic elements with Javascript. I can add BUT I can't remove! I can't Solve Problem. I'm confused! :(

My Code:

<script type="text/javascript">
//+Element
function addElement(div) {
  var ni = document.getElementById(div);
  var numi = document.getElementById('numVal');
  var num = (document.getElementById('numVal').value -1)+ 2;
  numi.value = num;
  var newdiv = document.createElement('div');
  newdiv.setAttribute('id',num);
  var unum="'"+div+"','"+num+"'";
  newdiv.innerHTML ='<input id="t" type="tel" placeholder="Tel.'+num+'" name="t'+num+1+'"><img id="del" onClick="removeElement('+unum+');" alt="del" src="images/del.gif" />';
  ni.appendChild(newdiv);
}
//-Element
function removeElement(divNum,div) {
  var d = document.getElementById(div);
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
}
</script>

    <form>
    <input type="hidden" value="0" id="numVal" />
    <div id="m">
        <div id="h125">
            <div class="fb">
                <input id="t" type="tel" placeholder="Tel.">
                <img id="add" Alt="add" src="images/add.gif" onclick="addElement('h125');" />
            </div>
        </div>
    </div>
    </form>

Thanks


回答1:


Is this what you are trying to achieve? If so, when you mixed up ids in removeElement function.

//+Element
function addElement(div) {
  var ni = document.getElementById(div);
  var numi = document.getElementById('numVal');
  var num = (document.getElementById('numVal').value -1)+ 2;
  numi.value = num;
  var newdiv = document.createElement('div');
  newdiv.setAttribute('id',num);
  var unum="'"+div+"','"+num+"'";
  newdiv.innerHTML ='<input id="t" type="tel" placeholder="Tel.'+num+'" name="t'+num+1+'"><img id="del" onClick="removeElement('+unum+');" alt="del" src="images/del.gif" />';
  ni.appendChild(newdiv);
}
//-Element
function removeElement(divNum,div) {
  var d = document.getElementById(divNum);
  var olddiv = document.getElementById(div);
  d.removeChild(olddiv);
}
<form>
    <input type="hidden" value="0" id="numVal" />
    <div id="m">
        <div id="h125">
            <div class="fb">
                <input id="t" type="tel" placeholder="Tel.">
                <img id="add" Alt="add" src="images/add.gif" onclick="addElement('h125');" />
            </div>
        </div>
    </div>
    </form>



回答2:


document.getElementsById(divNum); should read: document.getElementById(divNum);

You need to delete the 's' after element. update Sorry, I didn't test before I answered. When you declare var unum in your addElement(div) function, you have your variable names backwards. It should read var unum="'"+num+"','"+div+"'";



来源:https://stackoverflow.com/questions/36575161/remove-dynamic-element-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!