Próbuję usunąć element, ale nie mogę zrozumieć, dlaczego element nie jest usuwany z tablicy w ostatniej linii funkcji usuwania elementu, ale element nie jest usuwany z tablicy danych Łączę tablicę, ale to również nie działa dla mnie, jeśli istnieje jest jakieś lepsze rozwiązanie, proszę mi pomóc

Jest w funkcji deleteitem

  //Constructor for student form
var studentForm = function(iD,name,city,college,course,age){
    this.id = iD;
    this.name = name;
    this.city = city;
    this.college = college;
    this.course = course;
    this.age = age;
}
//all data store here as object
var data = [];

//function to submit and display form
var submitForm = function(){

    //getInput data from the field
    var getInput = {
        name:document.querySelector('.name').value,
        city:document.querySelector('.city').value,
        college:document.querySelector('.college').value,
        course:document.querySelector('.course').value,
        age:document.querySelector('.age').value,
    }
    
    //store the data which you get previous to use that
    var input = getInput;
    //Create a new id
    var ID;
    if(data.length > 0){
       ID = data[data.length - 1].id +1;
    }else{
        ID =1;
    }
    //Use the constructor and make a new data
    var newForm = new studentForm(ID,input.name,input.city,input.college,input.course,input.age);
    //Add the student data into the ds
    data.push(newForm);
    //Display the data in the Document
    //html line to display data of object
    var html = '<tr id="id-%roll%"><td>%id%</td><td class="tname">%name%</td><td class="tcity">%city%</td><td class="tcollege">%college%</td><td class="tcourse">%course%</td><td class="tage">%age%</td><td><button class="delbtn">Delete</button></td></tr>';        
    //Replace the placeHOlder With actual data
    var newHtml = html;
    //newHtml = "<td class=\"id-%id%\">%id%</td>".replace(/%id%/g, ID)
    newHtml = newHtml.replace('%roll%',ID);
    newHtml = newHtml.replace('%id%',ID);
    newHtml = newHtml.replace('%name%',input.name);
    newHtml = newHtml.replace('%city%',input.city);
    newHtml = newHtml.replace('%college%',input.college);
    newHtml = newHtml.replace('%course%',input.course);
    newHtml = newHtml.replace('%age%',input.age);
    //Get the element which after you wants to print the data
    document.querySelector('.tablemain').insertAdjacentHTML('beforeend',newHtml);
    //Clearint the fields
    var fields = document.querySelectorAll('.name' + ', ' + '.city' + ', ' + '.college' + ', ' + '.course' + ', ' + '.age');
   //Convert it into array
    var fieldsArr = Array.prototype.slice.call(fields);
    //Loopthrough all fields to clear the fields
    fieldsArr.forEach(function(current,index,array){current.value = '';});
    fieldsArr[0].focus();
    
    //Deleting element
    // parent element class = table id = id delete button class =delbtn
    
    
    
    console.log(newForm);
    return newForm;
}
document.querySelector('.btn').addEventListener('click',submitForm);
    
    //Delete section
    //Deleting element
    // parent element class = table id = id delete button class =delbtn
document.querySelector('.table').addEventListener('click',delItem);
    function delItem(e){
        var iTemId,splitID;
       iTemId = e.target.parentNode.parentNode.id;
        if(iTemId){
       splitID = iTemId.split('-');
      var ElementID = parseInt(splitID[1]);
            var deleteItem = function(id){
             var ids = data.map(function(cur){
                return cur.id; 
             });
             var index = ids.indexOf(id);
                if(index !== -1){
                 data.slice(index,1);   
                }
            };
            deleteItem(ElementID);
        };
    };
    
  <input type="text" placeholder="name" class="name">
    <input type="text" placeholder="city" class="city">
    <input type="text" placeholder="college" class="college">
    <input type="text" placeholder="Course" class="course">
    <input type="number" placeholder="age" class="age">
    <button class="btn" value="submit">Submit</button>
    <div class="table">
    <table class="tablemain">
<tr class="table-heading"><th>ID</th><th>Name</th><th>City</th><th>College</th><th>Course</th><th>Age</th><th>Delete</th></tr>      
   </table>
    </div>
 
0
Azeez 3 kwiecień 2020, 19:06

3 odpowiedzi

Najlepsza odpowiedź

Splice i Slice są funkcjami JavaScript Array. Metoda splice() zwraca usunięte elementy w tablicy podczas mutowania oryginalnej tablicy, a metoda slice() zwraca wybrane elementy z tablicy jako nowy obiekt tablicy bez modyfikowania oryginalnej tablicy .

Użyłeś tutaj slice zamiast splice. Jeśli chcesz użyć slice, zwróć wynikową tablicę lub zamień slice na splice

if(index !== -1){
   data.splice(index,1);   
}

// Or
if(index !== -1){
   const newData = data.slice(index,1);   
}
1
Pushkin 3 kwiecień 2020, 16:19

Właśnie zmodyfikowałem funkcję delItem

  • usuń wiersz tabeli
  • ustaw indeks na -1 (ponieważ tablica zaczyna się od 0)
 //Constructor for student form
var studentForm = function(iD,name,city,college,course,age){
    this.id = iD;
    this.name = name;
    this.city = city;
    this.college = college;
    this.course = course;
    this.age = age;
}
//all data store here as object
var data = [];

//function to submit and display form
var submitForm = function(){

    //getInput data from the field
    var getInput = {
        name:document.querySelector('.name').value,
        city:document.querySelector('.city').value,
        college:document.querySelector('.college').value,
        course:document.querySelector('.course').value,
        age:document.querySelector('.age').value,
    }
    
    //store the data which you get previous to use that
    var input = getInput;
    //Create a new id
    var ID;
    if(data.length > 0){
       ID = data[data.length - 1].id +1;
    }else{
        ID =1;
    }
    //Use the constructor and make a new data
    var newForm = new studentForm(ID,input.name,input.city,input.college,input.course,input.age);
    //Add the student data into the ds
    data.push(newForm);
    //Display the data in the Document
    //html line to display data of object
    var html = '<tr id="id-%roll%"><td>%id%</td><td class="tname">%name%</td><td class="tcity">%city%</td><td class="tcollege">%college%</td><td class="tcourse">%course%</td><td class="tage">%age%</td><td><button class="delbtn">Delete</button></td></tr>';        
    //Replace the placeHOlder With actual data
    var newHtml = html;
    //newHtml = "<td class=\"id-%id%\">%id%</td>".replace(/%id%/g, ID)
    newHtml = newHtml.replace('%roll%',ID);
    newHtml = newHtml.replace('%id%',ID);
    newHtml = newHtml.replace('%name%',input.name);
    newHtml = newHtml.replace('%city%',input.city);
    newHtml = newHtml.replace('%college%',input.college);
    newHtml = newHtml.replace('%course%',input.course);
    newHtml = newHtml.replace('%age%',input.age);
    //Get the element which after you wants to print the data
    document.querySelector('.tablemain').insertAdjacentHTML('beforeend',newHtml);
    //Clearint the fields
    var fields = document.querySelectorAll('.name' + ', ' + '.city' + ', ' + '.college' + ', ' + '.course' + ', ' + '.age');
   //Convert it into array
    var fieldsArr = Array.prototype.slice.call(fields);
    //Loopthrough all fields to clear the fields
    fieldsArr.forEach(function(current,index,array){current.value = '';});
    fieldsArr[0].focus();
    
    //Deleting element
    // parent element class = table id = id delete button class =delbtn
    
    
    
    console.log(newForm);
    return newForm;
}
document.querySelector('.btn').addEventListener('click',submitForm);
    
    //Delete section
    //Deleting element
    // parent element class = table id = id delete button class =delbtn
document.querySelector('.table').addEventListener('click',delItem);
    function delItem(e){
    // Delete table row
    document.getElementById(e.target.parentNode.parentNode.id).remove();
        var iTemId,splitID;
       iTemId = e.target.parentNode.parentNode.id;
        if(iTemId){
       splitID = iTemId.split('-');
      var ElementID = parseInt(splitID[1]);
            var deleteItem = function(id){
             var ids = data.map(function(cur){
                return cur.id; 
             });
             var index = ids.indexOf(id);
                if(index !== -1){
                 // delete array in data (array start with 0)
                 data = data.slice(index-1,1);   
                }
            };
            deleteItem(ElementID);
        };
    };
  <input type="text" placeholder="name" class="name">
    <input type="text" placeholder="city" class="city">
    <input type="text" placeholder="college" class="college">
    <input type="text" placeholder="Course" class="course">
    <input type="number" placeholder="age" class="age">
    <button class="btn" value="submit">Submit</button>
    <div class="table">
    <table class="tablemain">
<tr class="table-heading"><th>ID</th><th>Name</th><th>City</th><th>College</th><th>Course</th><th>Age</th><th>Delete</th></tr>      
   </table>
    </div>
0
Vernon Jian Hao 3 kwiecień 2020, 16:31

W przypadku przyszłych pytań otrzymasz więcej odpowiedzi, jeśli możesz maksymalnie uprościć swoje pytanie. Kod, który opublikowałeś, jest trochę trudny do zrozumienia.

Biorąc to pod uwagę, myślę, że problem jest tutaj data.slice(index,1);. Array.prototype.slice nie zmienia oryginalnej tablicy. Zwraca nową tablicę. Z tego powodu czasami ludzie używają go do tworzenia kopii tablicy, aby uniknąć mutacji za pomocą czegoś takiego jak const arrCopy = originalArr.slice();.

Myślę, że szukasz metody tablicowej splice.

Mam nadzieję, że to przybliży Cię. Gdzie zadeklarowano data? Widzę, że robisz z nim różne rzeczy i traktujesz go jako zmienną globalną, ale nie jesteś pewien, gdzie ją deklarujesz.

0
sdotson 3 kwiecień 2020, 16:17