2011-07-27 199 views
6

我有一個場景,我點擊一個元素說#stationLink。當我再次點擊它時,我想知道該元素是否已被點擊。我曾試圖如何知道一個元素是否已被點擊jquery

var a=false; 
$("#stationLink").click(function(){ 
    $(this).click(function(){ 
    a = true 
    }); 
    console.log(a); 
}); 

我越來越false兩次則僅true ..我想我失去了一些東西。或者還有其他方法可以做到嗎?

回答

9

這應該做你想做的(包括保持一個計數器,我已經看到你在一些評論想)

$("#stationLink").click(function(e){ 
    var $this = $(this); 
    var clickCounter = $this.data('clickCounter') || 0; 
    // here you know how many clicks have happened before the current one 

    clickCounter += 1; 
    $this.data('clickCounter', clickCounter); 
    // here you know how many clicks have happened including the current one 

}); 

使用您存儲與DOM元素櫃檯.data()方法,該方法您可以將相同的處理程序應用於多個元素,因爲每個元素都有自己的計數器。

demo at http://jsfiddle.net/gaby/gfJj6/1/

1

我通常是.chosen命名或.x_visited類添加到它

$("#stationLink").click(function(){ 
$(this).addClass("x_visited") 
} 

然後你就可以覈對與$("#stationLink").hasClass('x_visited');例如

1
var stationLink_clicked = false; 

$("#stationLink").click(function(){ 
    console.log('Already clicked? ' + stationLink_clicked); 
    /* do stuff */ 

    stationLink_clicked = true; 
}); 
4

你可以添加你可以檢查一個屬性:

$("#stationLink").click(function(){ 
    $(this).attr("hasBeenClicked", "true"); 
}); 

我不喜歡使用全局變量來保持這個項目被點擊的原因很簡單,如果你必須跟蹤多個項目,那麼它可能會有點混亂。我比較喜歡屁股類或屬性,你可以將它是否已被點擊

4

這個版本的元素上看到記錄的點擊數:

$("#stationLink").click(function() { 
    var clickCount = $(this).data('clickCount') || 0; 

    if (clickCount > 0) { 
     // clicked `clickCount` times 
    } 

    $(this).data('clickCount', clickCount + 1); 
}); 

要重置點擊次數使用

$("#stationLink").data('clickCount', 0); 
+0

有沒有什麼辦法可以知道元素被點擊了多少次? –

+0

是的。我會更新答案,包括一會兒計算。 –

3

這是因爲您實際上是在第一次點擊該元素時綁定了另一個點擊處理程序。只要刪除該處理程序。

var clicked = false; 
$("#stationLink").click(function(){ 
    clicked = true 
    //Code to toggle if required. 
}); 
2

另一種選擇是:

$('#stationLink').click(function(){ 
    $(this).data('clicked', true); 
}); 

console.log($(this).data('clicked')); 

我覺得這是最使用jQuery UI的方法。

相關問題