2012-07-31 89 views
1

我使用toggleClass().看選擇哪個菜單選項的選擇菜單:如何查看哪個元素先被點擊?

$('.img1, .img2, .text1, .tex2').click(function() { 
    $(this).toggleClass('selected'); 
}); 

我的選擇菜單中的工作方式是,如果兩個元素具有類selected然後會有些事情發生。例如:

if ($('.img1').hasClass('selected') && ('.text1').hasClass('selected')) { 
    // do something 
} 

這一切能夠完美,但是我想從吸取兩個imgs或兩個texts禁用用戶。我想要這樣做的方式只是將第一個選定的元素從選定的類中移除,並將第二個選定的元素保持選中狀態。例如:

if ($('.img1').hasClass('selected') && ('.img2').hasClass('selected')) { 
     // remove selected from the element that was first clicked and keep selected on the element that was clicked second 
} 

實現此目的的最佳方法是什麼?提前致謝。

+0

爲什麼要投票? – iambriansreed 2012-07-31 18:30:55

+0

我upvoted你的答案... – Jon 2012-07-31 18:33:09

+0

我問你的問題上的DV。 – iambriansreed 2012-07-31 18:33:53

回答

1

嘗試:

$('.img1, .img2').click(function() { 
    $('.img1, .img2').removeClass('selected').filter(this).toggleClass('selected'); 
}); 
$('.text1, .text2').click(function() { 
    $('.text1, .text2').removeClass('selected').filter(this).toggleClass('selected'); 
}); 

分離你的點擊事件將確保只有每個類型的物品的一個選擇。

此外,請確保您沒有在做$('this')

它應該是$(this)

+1

工程很好,做得非常好。謝謝。 – Jon 2012-07-31 18:28:25

+0

@Ferri你用最新的代碼,'.filter(this)'來試試嗎? – iambriansreed 2012-07-31 18:29:11

+1

是的,它的工作原理。 – Jon 2012-07-31 18:30:19

0

這會將類名稱「first」添加到被點擊的第一個項目。其餘的由你決定。

$('.img1, .img2, .text1, .tex2').click(function() { 
    $('this').toggleClass('selected'); 
    if($('.first').length==0) { 
     $('this').addClass('first'); 
    } 
}) 
0

也許,如果你有這樣的持續跟蹤所點擊物品的ID的數組,你可以使用:

var clickArr = new Array(); 
$('.img1, .img2, .text1, .tex2').click(function() 
{ 
    $('this').toggleClass('selected'); 
    clickArr.push($(this).attr("id")); 
}); 

然後,當你發現其中兩個被選中的點:

if ($('.img1').hasClass('selected') && ('.img2').hasClass('selected')) 
{ 
    $("#"+clickArr[0]).removeClass("selected"); 
    clickArr.shift(); 
} 

這可能會很棘手,因爲每次「處理選擇」時都需要清空數組。但也許這可以讓你開始。

相關問題