2013-09-05 73 views
4

我試圖創建一個浮動div誰顯示時,按鈕被觸發。這並不難,但是當我按下按鈕時,頁面會自動重新加載。我不知道爲什麼。jQuery.Click方法重新加載頁面

我試圖使用Bootstrap的Popover,但由於同樣的問題,它沒有像預期的那樣工作。當彈出窗口被觸發時,頁面重新加載,彈出窗口顯然消失。

我正在使用RoR,只是說如果這將有助於找出問題。

我在文檔的底部是這樣的:

<a href="#" class="btn btn-small btn-warning" id="example">Show</a> 

<script type="text/javascript"> 
    $(document).ready(function() { 
     console.log("Page is loaded."); 

     // Custom Popover 
     $("#example").click(function() { 
      console.log("Showing"); 
     }); 
    }); 
</script> 

第一console.log內準備功能顯示在頁面加載時。當我觸發按鈕「顯示」時,console.log再次顯示在瀏覽器的控制檯中。這沒有任何意義。

謝謝!

回答

14

您需要使用preventDefault()阻止鏈接的默認行爲:

$("#example").click(function(e) { 
    e.preventDefault(); 
    console.log("Showing"); 
}); 
1

你有問題,而不是class你已經使用href

<a href="#" class="btn btn-small btn-warning" id="example">Show</a> 
+0

對不起,在我原來的html文件我有href放。我忘了在上面的例子中添加它。這不是問題。對不起。 –

1

你有兩個問題:

您正在將您的課程設置爲您的href屬性而不是class

<a href="#" class="btn btn-small btn-warning" id="example">Show</a> 

你會想從下面的href停止瀏覽器鏈接時被調用:

$("#example").click(function(e) { 
    e.preventDefault(); // don't follow href 
    console.log("Showing"); 
}); 
1

你必須停止錨做它的默認功能,加載頁面中指定的HREF 。 此代碼應該做的伎倆:

$("#example").click(function(event) { 
    event.preventDefault(); 
    console.log("Showing"); 
}); 
1

這不能,它應該工作正常。必須有其他問題,請填寫完整頁面。

$(document).ready(function() { 

    console.log("Page is loaded."); 

    // Custom Popover 
    $("#example").click(function() { 
     console.log("Showing"); 
    }); 

});

See here

1

在這裏你可以找到一個完全工作的例子。 test here

$(document).ready(function() 
{ 
    console.log("Page is loaded."); 

    $("#example").click(function(e) 
    { 
     e.preventDefault(); 
     alert("works"); 
    }); 

});