簡體   English   中英

jQuery.Click方法重新加載頁面

[英]jQuery.Click method reloads the page

我正在嘗試創建一個浮動div,當按鈕被觸發時它會出現。 這並不難,但是當我按下按鈕時,頁面會自動重新加載。 我不知道為什么。

我試圖使用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內部就緒功能。 當我觸發“Show”按鈕時,該console.log再次顯示在瀏覽器的控制台中。 這沒有任何意義。

謝謝!

您需要使用preventDefault()來停止鏈接的默認行為:

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

你有問題,而不是你用過hrefclass

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

你有兩個問題:

您在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");
});

你必須停止錨點來執行它的默認功能,加載指定其href的頁面。 這段代碼可以解決這個問題:

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

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

 $(document).ready(function() {

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

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

});

看這里

在這里你可以找到一個完整的例子。 在這里測試

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

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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM