我正在建立一个简单的过滤系统,我只是想添加一个字符串数组,并删除它,如果它已经存在点击一个链接。我会尽力解释尽我所能..jquery - 简单的数组,如果它不在那里已经推入项目,删除项目,如果它存在
$(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();
});
});
你可以尝试'indexof'你的字符串对数组?如果它返回-1,那么'push',如果它大于-1,那么''pop' – MilkyWayJoe 2012-03-07 15:40:29