A good JavaScript to add/remove items from/to array?

前端 未结 4 1841
名媛妹妹
名媛妹妹 2021-02-06 10:30

folks! Today I created this script that has the following functionality:

  • add new items to array
  • list all items from the array
  • remove an item from
4条回答
  •  春和景丽
    2021-02-06 11:05

    You should use array.splice(position,nbItems)

    function removeRecord (i) {
        foodList.splice(i, 1); // remove element at position i
        var newFood = "";
        for (var i = 0; i < foodList.length; i++) {
            newFood += "X "
                + foodList[i] + " 
    "; }; document.getElementById('foods').innerHTML = newFood; }

    http://jsfiddle.net/3b4qp/5/

    Now using JQuery:

    $(function(){
        $(document).on('click','input[type=submit]',function(){
            $('#foods')
               .append('
    X ' + $('#addFood').val() + '
    '); }); $(document).on('click','.item',function(){ $(this).parent().remove(); }); });

    http://jsfiddle.net/jfWa3/

提交回复
热议问题