12

配列にすでに値があるかどうかを確認しようとしています。値が配列に存在しない場合は配列に追加する必要があり、値が既に存在する場合は削除する必要があります。

var selectArr = [];
$('.media-search').mouseenter(function(){
    var $this = $(this);
    $this.toggleClass('highlight');
}).mouseleave(function(){
    var $this = $(this);
    $this.toggleClass('highlight');

}).on('click',function(){
    var dataid = $(this).data('id');

    if(selectArry){ // need to somehow check if value (dataid) exists.
    selectArr.push(dataid); // adds the data into the array
    }else{
    // somehow remove the dataid value if exists in array already
    }


}); 
4

3 に答える 3

36

メソッドを使用しinArrayて値を検索し、 メソッドpushとメソッドを使用しspliceてアイテムを追加または削除します。

var idx = $.inArray(dataid, selectArr);
if (idx == -1) {
  selectArr.push(dataid);
} else {
  selectArr.splice(idx, 1);
}
于 2013-02-09T01:42:38.383 に答える