我正在建立一個簡單的過濾系統,我只是想添加一個字符串數組,並刪除它,如果它已經存在點擊一個鏈接。我會盡力解釋盡我所能..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