2009-06-10 27 views
7

我有一個簡單的點擊和顯示,點擊和隱藏按鈕,但是當我點擊它時,頁面會停留在頁面的頂部。無論如何要防止這一點?所以當我點擊按鈕時,我會呆在瀏覽器的同一個地方?jQuery點擊將我帶到頁面頂部。但我想留在我的位置

我的代碼..

$('#reportThis').hide(); 

$('#flagThis').click(function() { 
    $('#reportThis').show("slow"); 
}); 
$('#submitFlag').click(function() { 
    $('#reportThis').hide("slow"); 
}); 

回答

17

試試這個:

$('#reportThis').hide(); 

$('#flagThis').click(function (evt) { 
     $('#reportThis').show("slow"); 
     evt.preventDefault(); 
}); 
$('#submitFlag').click(function (evt) { 
     $('#reportThis').hide("slow"); 
     evt.preventDefault(); 
}); 
+0

哇感謝katrillion! – Trip 2009-06-10 17:15:25

4

你可能是有約束力這個點擊的<一個>標籤,它有一個默認的動作。爲了防止這種情況,你可以使用另一個標籤像<DIV>或者你可以這樣做:

$('#flagThis').click(function (event) { 
     $('#reportThis').show("slow"); 
     event.preventDefault(); 
}); 
+0

爲什麼要投票?哪裏不對? – 2009-06-10 16:51:10

+0

+1取消,沒有錯 – 2009-06-10 16:56:57

4

嘗試在click函數返回false

$('#reportThis').hide(); 

$('#flagThis').click(function() { 
     $('#reportThis').show("slow"); 
     return false; 
}); 
$('#submitFlag').click(function() { 
     $('#reportThis').hide("slow"); 
     return false; 
}); 
3

更改超鏈接指向一個不存在的錨,像這樣:

<a href="#IDontExist" id="flagThis">Flag</a> 

或者,讓你的處理器返回false,像這樣:

$('#reportThis').hide(); 

$('#flagThis').click(function() { 
    $('#reportThis').show("slow"); 
    return false; 
}); 
$('#submitFlag').click(function() { 
    $('#reportThis').hide("slow"); 
    return false; 
}); 
0

如果您使用的是<button>元素,請不要忘記設置type屬性。

<button type="button">My Button</button> 

有些瀏覽器默認的提交,將帶你回到你的頁面的開始。

無論如何,這是我出錯的地方,在這裏什麼也看不到,因此我想我會爲未來的讀者分享我的兩分錢。

相關問題