如何从jquery中的列表中删除元素?

时间:2015-10-19 03:26:39

标签: javascript jquery

我正在尝试使用JavaScript和jQuery创建一个简单的列表。我正在使用oops的JavaScript概念。我可以在列表中添加新元素。我遇到一个问题,我有两个按钮来更新和删除行。我创建了一个数组,其中包含所有对象。我想如果用户点击删除按钮,它将从数组中删除,也从列表中删除。如果用户更新项目,它也应该在数组和列表中更新

我试过这样做

https://jsfiddle.net/0dky3txz/3/

function Phonebook(){
    this.phoneBookArray=[];
    var defaultvalue= [{name:"abc",phonenumber:989123},{name:"pqr",phonenumber:9891462}]
    this.phoneBookArray=defaultvalue;
    console.log(this.phoneBookArray)
   }
Phonebook.prototype.addItem=function(username,phoneNumber){
    this.phoneBookArray.push({name:username,phonenumber:phoneNumber})
    this.displayItem();
}

Phonebook.prototype.displayItem=function(){
    $("#phonelist").html('');
    for(var i=0;i<this.phoneBookArray.length;i++){
        $("#phonelist").append('<li><span>'+this.phoneBookArray[i].name+'</span><span>'+       this.phoneBookArray[i].phonenumber+'</span><span><button class="del">delete</button></span><span><button class="update">update</button></span></li>')
    }
}

var phonedir=new Phonebook();
phonedir.displayItem();
$('#addItem').click(function(){

    var name=$('#nameEdit').val();
     var phone=$('#numberEdit').val();

    if(name!=''&& phone!=""){
       phonedir.addItem(name,phone);
        $('#nameEdit').val('');
        $('#numberEdit').val('');
    }else{
     alert('please enter number and name')   
    }

})


$('.del').click(function(){
    //try to delete item from list as well as from phoneBookArray
   console.log($(this).parent('li'))

})

$('.update').click(function(){
    //try to update item from list as well as from phoneBookArray

    // try to get selected item and fill on text field and update the list
   //console.log($(this).parent('li'))

})

0 个答案:

没有答案