Javascript jQuery-使用delete image从数组中删除li

Javascript jQuery-使用delete image从数组中删除li,javascript,jquery,arrays,cookies,Javascript,Jquery,Arrays,Cookies,我正在尝试创建一个可以添加和删除元素的菜单栏。到目前为止还不错,但当我尝试删除它们时,我遇到了问题。我已经玩了几个小时,现在我想知道是否整个过程可以变得更简单(也许是一个对象?) 无论如何,这里是完整的代码(80行),并附有注释 var tabs = $('.accountSelectNav'); var titles = []; var listItems = []; // when the page loads check if tabs need to be added to the ul

我正在尝试创建一个可以添加和删除
  • 元素的菜单栏。到目前为止还不错,但当我尝试删除它们时,我遇到了问题。我已经玩了几个小时,现在我想知道是否整个过程可以变得更简单(也许是一个对象?)

    无论如何,这里是完整的代码(80行),并附有注释

    var tabs = $('.accountSelectNav');
    var titles = [];
    var listItems = [];
    // when the page loads check if tabs need to be added to the ul (menu bar)
    $(document).ready(function(e) {
        if ($.cookie('listItems') != null) {
            console.log('not null');
                //return "listItems" to it's array form.
            listItems = JSON.parse($.cookie('listItems'));
            $('.accountSelectNav').append(listItems);
        }
    });
    
    $('.selectTable td:first-child').on('click', function(e) {
        $('#home_select').removeClass('navHighlight');
        //grab the text value of this cell
        title = $(this).text();
        $.ajax({
            url:'core/functions/getAccountId.php',
            type: 'post',
            data: {'title' : title}
        }).fail (function() {
            alert('error');
        }).done(function(data) {
            accountId = $.trim(data);
            // store values in the cookie
            $.cookie('account_id', accountId, {expires : 7});
            $.cookie('title', title, {expires : 7});
            window.location = ('home_table.php');
        });
    
        // make sure the value is NOT currently in the array. Then add it 
        var found = jQuery.inArray(title, titles);
        if (found == -1) {
            titles.push(title);
            addTab();
        }
    
        // make sure the value is NOT currently in the array. Then add it
        found = jQuery.inArray(title, listItems);
        if (found == -1) {
            addListItem();
            //place <li>'s in cookie so they may be used on multiple pages
            $.cookie('listItems', JSON.stringify(listItems));
        };
    });
    
    $("body").on("click", ".deleteImage", function (e) {
        var removeTitle = $(this).closest('li').find('a').text();
        var removeItem = $(this).closest('li')[0].outerHTML;
    
        //remove title from "titles" array
        titles = jQuery.grep(titles, function (value) {
            return value != removeTitle;
        });
        //remove <li> from "listItems" array
        listItems = jQuery.grep(listItems, function (value) {
            return value != removeItem;
        });
        // this shows the <li> is still in the listItemsarray
        console.log(listItems); 
        // put the array back in the cookie
        $.cookie('listItems', JSON.stringify(listItems));
        removeTab(this);
    });
    
    $("body").on("mouseover", ".accountSelectNav li", function(e) {
        $(this).find('.deleteImage').show();
    });
    
    $("body").on("mouseleave", ".accountSelectNav li", function(e) {
        $(this).find('.deleteImage').hide();
    });
    
    function addTab() {
        tabs.append('<li class="navHighlight">' + '<a href="#">' + title + '</a>' + '<a href="#">' + '<img src="images/delete.png" class="deleteImage"/>' + '</a>' + '</li>');
    };
    
    function removeTab(del) {
        $(del).closest('li').remove();
    }
    
    function addListItem() {
        var s = ('<li class="navHighlight">' + '<a href="#">' + title + '</a>' + '<a href="#">' + '<img src="images/delete.png" class="deleteImage"/>' + '</a>' + '</li>');
        listItems.push(s);
    }
    
    var tabs=$('.accountSelectNav');
    var标题=[];
    var listItems=[];
    //加载页面时,检查是否需要将选项卡添加到ul(菜单栏)
    $(文档).ready(函数(e){
    如果($.cookie('listItems')!=null){
    log('notnull');
    //将“listItems”返回到其数组形式。
    listItems=JSON.parse($.cookie('listItems'));
    $('.accountSelectNav')。追加(列表项);
    }
    });
    $('.selectTable td:first child')。在('click',函数(e)上{
    $('home'u select').removeClass('navHighlight');
    //获取此单元格的文本值
    title=$(this.text();
    $.ajax({
    url:'core/functions/getAccountId.php',
    键入:“post”,
    数据:{'title':title}
    }).fail(函数(){
    警报(“错误”);
    }).完成(功能(数据){
    accountId=$.trim(数据);
    //在cookie中存储值
    $.cookie('account_id',accountId,{expires:7});
    $.cookie('title',title,{expires:7});
    window.location=('home_table.php');
    });
    //确保该值当前不在数组中。然后添加它
    var found=jQuery.inArray(title,titles);
    如果(找到==-1){
    标题。推送(标题);
    addTab();
    }
    //确保该值当前不在数组中。然后添加它
    found=jQuery.inArray(标题、列表项);
    如果(找到==-1){
    addListItem();
    //将
  • 放在cookie中,以便可以在多个页面上使用 $.cookie('listItems',JSON.stringify(listItems)); }; }); $(“正文”)。在函数(e)中(“单击”、“删除图像”){ var removeTitle=$(this.closest('li').find('a').text(); var removietem=$(this).closest('li')[0].outerHTML; //从“标题”数组中删除标题 titles=jQuery.grep(标题、函数(值){ 返回值!=删除标题; }); //从“listItems”数组中删除
  • listItems=jQuery.grep(listItems,函数(值){ 返回值!=removeItem; }); //这表明
  • 仍在listItemsarray中 console.log(列表项); //将数组放回cookie中 $.cookie('listItems',JSON.stringify(listItems)); 移除(这个); }); $(“body”)。在(“鼠标悬停”,“帐户选择导航”,函数(e){ $(this.find('.deleteImage').show(); }); $(“body”)。在(“mouseleave”、“.accountSelectNav li”上,函数(e){ $(this.find('.deleteImage').hide(); }); 函数addTab(){ tabs.append('
  • '+'++'
  • '); }; 功能删除选项卡(del){ $(del).最近('li').remove(); } 函数addListItem(){ var s=('
  • '+'+'+'
  • '); 列表项。推送; }
    你看,我有两个长度相等的数组,它们的长度应该总是相同的。一个存储要在选项卡中显示的标题,另一个保存将附加到
    • 的html。从数组中删除标题没有问题。然而,从它的数组中删除
    • 却成了一个相当大的麻烦。你看,当我得到
    • 元素后,它膨胀了,里面的html与放入的内容不完全匹配,浏览器添加了样式元素

      例如,变量“removietem”表示要删除的所选
    • 的html值。看起来是这样的:

      <li class="navHighlight"><a href="#">Test1</a><a href="#"><img src="images/delete.png" class="deleteImage" style="display: inline;"></a></li> 
      
    • 但我的数组“listItems”中的值如下所示:

      <li class="navHighlight"><a href="#">Test1</a><a href="#"><img src="images/delete.png" class="deleteImage"/></a></li> 
      
      $.cookie('titles', JSON.stringify(titles));
      
      removeTab(this);
      
      function removeTab(del) {
          $(del).closest('li').remove();
      }
      
    • 因此,我尝试将其从阵列中删除时总是失败,因为它们不是完美匹配的

      现在我的问题是如何删除此
    • 项?还有没有一种更简单的方法来完成整个过程,而我却没有看到

      谢谢你抽出时间

      编辑

      随叫随到

      最简单的解释方法

      单击指向小提琴的链接
      单击“应用程序名称”列中的任意单元格
      这会将
    • 添加到表上方的
      (菜单)
      当您将鼠标悬停在
    • 上时,会出现一张图片
      单击图片
      这将从
      和数组列表项中删除


    • 现在它不

      在使其更易于检查的过程中,我使用了您的JSFIDLE并执行了以下操作:

      • 删除了额外的console.log和注释
      • 删除了与cookies的交互(因为我一开始没有cookies,我想它们不会只是第一个场景)
      在这样做之后,我达到了一个点(你可以看到),在那里所需的功能刚刚工作

      我甚至删除了ajax的东西,因为那个警报让我发疯。()

      既然这样做很好,我猜你的问题就在我删除的字里行间

      您对Cookie的使用情况如下:

    • 加载现有选项卡并重新添加它们的步骤
    • 保存不再使用的
      帐户id
      标题
    • 要在添加新项后保留
      列表项
    • 然后,我用您的小提琴版本打开控制台,javascript的执行在
      $处停止。cookie()
      错误为
      未定义不是函数

      这清楚地表明Fiddle中存在的问题是jQuery.cookie不存在,因此这些调用正在停止脚本其余部分的执行。这也解释了为什么会这样
      $.cookie('titles', JSON.stringify(titles));
      
      $(document).ready(function() {
          if ($.cookie('titles') != null) {
              titles = JSON.parse($.cookie('titles'));
          }
      });
      
      for(var i = 0; i < titles.length; i++) {
          var str = titles[i];
          var listItem = '<li class="navHighlight">' 
                          + '<a href="#">' 
                          + str 
                          + '</a>' 
                          + '<a href="#">' 
                          + '<img src="images/delete.png" class="deleteImage"/>' 
                          + '</a>' 
                          + '</li>';
          $('.accountSelectNav').append(listItem);
      }
      
      $("body").on("click", ".deleteImage", function (e) {
          // grabs the text value of my li, which I want to remove
          var removeTitle = $(this).closest('li').find('a').text();
          // runs through my titles array and returns an array without the value above
          titles = jQuery.grep(titles, function (value) {
              return value != removeTitle;
          });
      });
      
      $.cookie('titles', JSON.stringify(titles));
      
      removeTab(this);
      
      function removeTab(del) {
          $(del).closest('li').remove();
      }