2012-01-03 2 views
1

У меня есть следующий код, который добавляет параметр загрузки файла в div и удаляет последний добавленный элемент.Добавить элементы и удалить конкретный, добавленный через Javascript

<script language="javascript" type="text/javascript"> 
    function add(type) { 
     var element = document.createElement("input"); 
     element.setAttribute("type", type); 
     element.setAttribute("value", type); 
     element.setAttribute("name", type); 
     element.setAttribute("style", "width: 500px;"); 
     var newfile = document.getElementById("uploadhere"); 
     newfile.appendChild(element);   
    } 
    function remove() { 
     var newfile = document.getElementById("uploadhere"); 
     newfile.removeChild(newfile.lastChild); 
    } 

</script> 

Я пытаюсь выяснить способ, чтобы удалить определенный элемент, добавленный вместо того, чтобы просто удаление последнего элемента, вероятно, с индексом каким-то образом. Или просто нажмите кнопку удаления рядом с созданным элементом.

отредактирован, чтобы добавить мое решение

Вот как я решил проблему

<script language="javascript" type="text/javascript"> 
     var i = 0; 
     function add(type) {    
      var element = document.createElement("input"); 
      element.setAttribute("type", type); 
      element.setAttribute("value", type); 
      element.setAttribute("name", type); 
      element.setAttribute("style", "width: 500px;"); 
      element.setAttribute("id", "element-" + i); 
      var removebutton = document.createElement("input"); 
      removebutton.type = "button"; 
      removebutton.value = "Remove"; 
      removebutton.setAttribute("id", "remove-" + i); 
      removebutton.setAttribute("onclick", "remove(" + i + ")"); 
      var newfile = document.getElementById("uploadhere"); 
      newfile.appendChild(element); 
      newfile.appendChild(removebutton); 
      i++;      
     } 
     function remove(id) {    
      document.getElementById("uploadhere").removeChild(document.getElementById("element-" + id));    
      document.getElementById("uploadhere").removeChild(document.getElementById("remove-" + id)); 
     } 

    </script> 
+1

Мне нравится идея удаления кнопки рядом с созданным элементом. Делает логику удаления легко реализуемой. –

ответ

1

Попробуйте это:

<script language="javascript" type="text/javascript"> 
    var i = 1; 
    function add(type) { 
     var element = document.createElement("input"); 
     element.setAttribute("type", type); 
     element.setAttribute("value", type); 
     element.setAttribute("name", type); 
     element.setAttribute("style", "width: 500px;"); 
     element.setAttribute("id", "element-" + i++); 
     var newfile = document.getElementById("uploadhere"); 
     newfile.appendChild(element);   
    } 
    function remove(id) { 
     document.getElementById("uploadhere").removeChild(document.getElementById("element-" + i)); 
    } 

</script> 
0

Один вариант, как вы сказали, чтобы использовать индекс:

function remove(index) 
{ 
    var newfile = document.getElementById("uploadhere"); 
    newFile.removeChild(newfile.childNodes[index]) 
} 

И удалите линия newfile.removeChild в вашей функции «добавить»

Другой вариант, как вы сказали, заключается в использовании кнопки, которая может быть проще с точки зрения удобства пользования. Мое предпочтение состоит в том, чтобы положить все в таблицу, чтобы сделать ее более аккуратной:

<table> 
    <tbody id="uploadhere"> 
    </tbody> 
</table> 

<script> 
    var newfile = document.getElementById("uploadhere"); 

    function add(type) { 
    var element = document.createElement("input"); 
    element.setAttribute("type", type); 
    element.setAttribute("value", type); 
    element.setAttribute("name", type); 
    element.setAttribute("style", "width: 500px;"); 

    // Create your button 
    var button = document.createElement("button"); 
    button.onclick = "newfile.removeChild(this.parentNode.parentNode)"; 
    var text = document.createTextNode("Remove"); 
    button.appendChild(text); 

    // Create a table row in which to put the data 
    var row = newFile.insertRow(-1); 

    // Create a table cell in which to put your "input" element 
    var cell1 = row.insertCell(-1); 
    cell1.appendChild(element); 

    // Create a table cell in which to put your button 
    var cell2 = row.insertCell(-1); 
    cell2.appendChild(button); 
    } 
</script> 
Смежные вопросы