jQuery的 - 简单阵列,推项目中如果不存在的话,删除项目,如果它的存在 [英] Jquery - Simple Array, pushing item in if its not there already, removing item if it is there

查看:107
本文介绍了jQuery的 - 简单阵列,推项目中如果不存在的话,删除项目,如果它的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个简单的过滤系统,我只是想将一个字符串添加到一个数组,如果它已经在那里上的链接的点击将其删除。我会尽力解释尽我所能。

  $(文件)。就绪(函数(){
    //所以我开始与空数组
    变种滤波器[];
    //点​​击一个链接时,我想将它添加到阵列中..
    $('李一',上下文)。点击(函数(五){
        //所以我得到了点击的项目实例的数据,事件属性保存的值:约翰
        newFilter = $(本).attr(数据事件');
        //这是我遇到问题,我想测试,看看是否字符串我现在有
        //在newFilter'是阵列中已经或不..如果它是在阵列中我
        //想删除它,但如果它不数组中存在我想添加它..
        如果(jQuery.inArray(newFilter,过滤器){
            //添加到阵列
        }其他{
           //从数组中删除
        };
    亦即preventDefault();
    });
});


解决方案
返回首页

$ .inArray() 1 如果被发现,而该项目其他方面(就像<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf\">indexOf()确实,支持时)。因此,你可以写这样的:

  VAR发现= jQuery.inArray(newFilter,过滤器);
如果(发现&GT; = 0){
    //元素被发现,将其删除。
    filters.splice(发现,1);
}其他{
    //元素没有被发现,添加它。
    filters.push(newFilter);
}

I'm building a simple filtering system, I simply want to add a string to an array and remove it if its already there on click of a link. I'll try to explain the best I can..

$(document).ready(function(){
    //so I start with an empty array
    var filters [];
    //when a link is clicked I want to add it to the array..
    $('li a', context).click(function(e){
        //so I get the value held in the data-event attribute of the clicked item example: "john"
        newFilter = $(this).attr('data-event');
        //this is where I get stuck, I want to test to see if the string I now have
        //in 'newFilter' is in the array already or not.. if it is in the array I
        //want to remove it, but if it doesnt exist in the array i want to add it..
        if(jQuery.inArray(newFilter, filters){
            //add to array
        } else {
           //remove from array
        };
    e.preventDefault();
    });
});

解决方案

$.inArray() returns the index of the item if it is found, and -1 otherwise (just like indexOf() does, when supported). Therefore, you can write something like:

var found = jQuery.inArray(newFilter, filters);
if (found >= 0) {
    // Element was found, remove it.
    filters.splice(found, 1);
} else {
    // Element was not found, add it.
    filters.push(newFilter);
}

这篇关于jQuery的 - 简单阵列,推项目中如果不存在的话,删除项目,如果它的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆