我正在构建一个简单的过滤系统,我只想将一个字符串添加到数组中,并在单击链接时将其删除(如果它已经存在)。我会尽力解释。
$(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() http://api.jquery.com/jQuery.inArray/如果找到则返回该项目的索引,并且-1
否则(就像指数() https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf确实如此,当支持时)。因此,你可以这样写:
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)