2017-02-09 104 views
0

我正在嘗試製作一個網站,每次用戶點擊鼠標時都會計數。我有這部分,但我還需要包括一個重置按鈕,用戶單擊它後,從0開始鼠標單擊計數器返回。jQuery鼠標點擊計數器 - 如何重置?

我無法弄清楚 - 如果我將var = 0文檔就緒,它重置,但點擊按鈕後,計數器永遠不會超過1.我不知道該怎麼做。

我的腳本 -

$(document).ready(function(){ 
    console.log("Here"); 


    $(document).click(function(e) { 
     $('#location').append("("+e.clientX+", "+e.clientY+")<br>"); 
    }); 

    var counter = 0; 
    $(document).click(function(e) { 
     counter++; 
     $("#mouseclick").text("Total mouse clicks: " + counter); 
    }); 

    $('button').click(function(e) { 
     e.stopPropagation(); // stop the event from propagating up the visual tree 
     $('#location').text(""); 
     $("#mouseclick").text("Total mouse clicks: 0"); 
    }); 

    $('button') 
}); 

我需要他們能夠點擊的「按鈕」和計數將重置。有什麼建議?

+0

第一計數器= 0;然後$(「#mouseclick」)。text(「總鼠標點擊次數:」+計數器); =) –

+0

什麼是「$('button')」最後? –

+0

在你的按鈕點擊事件中,只需設置'counter = 0' –

回答

1

您沒有重置櫃檯。請參閱this fiddle

$(document).ready(function(){ 
    console.log("Here"); 


$(document).click(function(e) { 
    $('#location').append("("+e.clientX+", "+e.clientY+")<br>"); 
}); 

var counter = 0; 
$(document).click(function(e) { 
    counter++; 
    $("#mouseclick").text("Total mouse clicks: " + counter); 
}); 

$('button').click(function(e) { 
    e.stopPropagation(); // stop the event from propagating up the visual tree 
    $('#location').text(""); 
    counter = 0; 
    $("#mouseclick").text("Total mouse clicks: 0"); 
}); 
+0

謝謝!我以爲我昨晚做了這個,但回想起來,我已經把var counter = 0;而不僅僅是counter = 0 ;. 謝謝! –

+0

其實,如果我可以問 - 爲什麼會var counter = 0;不工作,而不是counter = 0;?是否因爲變量已經定義,所以變得多餘? –

+0

如果您使用'var'關鍵字重新定義變量,它通常會引發錯誤。 – TricksfortheWeb

0

只需在$('button')。click()事件中添加counter = 0即可。

$('button').click(function(e) { 
    counter=0; 
    e.stopPropagation(); // stop the event from propagating up the visual tree 
    $('#location').text(""); 
    $("#mouseclick").text("Total mouse clicks: 0"); 
}); 
+0

哦,我的上帝......這很簡單。我認真地認爲我已經嘗試了一切。完全超越這個,哈哈。謝謝!! –