4

I'm trying to creating a floating div who shows up when a button is triggered. It's not hard, but when i press the button the page automatically reloads. I don't know why.

I tried to use Bootstrap's Popover, but it doesn't working as expected due to this same problem. When the popover is triggered, the page reloads and the popover obviously disappear.

I'm using RoR, just saying in case that would be useful to find out the problem.

I have something like this in document's bottom:

<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>

The first console.log inside ready function is shown when the page loads. When I trigger the button "Show", that console.log is again shown in browser's console. And that doesn't make any sense.

Thanks!

4

6 回答 6

16

您需要使用以下命令停止链接的默认行为preventDefault()

$("#example").click(function(e) {
    e.preventDefault();
    console.log("Showing");
});
于 2013-09-05T13:11:00.170 回答
1

这不可能,它应该可以正常工作。一定有其他问题,请填写您的完整页面。

 $(document).ready(function() {

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

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

});

看这里

于 2013-09-05T13:34:19.647 回答
1

你有问题,而不是class你用过href

<a href="#" class="btn btn-small btn-warning" id="example">Show</a>
于 2013-09-05T13:06:34.187 回答
1

在这里您可以找到一个完整的工作示例。 在这里测试

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

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

});

于 2013-09-05T14:12:48.393 回答
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");
});
于 2013-09-05T13:11:14.363 回答
1

您必须停止锚点以执行其默认功能,加载指定其 href 的页面。这段代码应该可以解决问题:

$("#example").click(function(event) {
     event.preventDefault();
     console.log("Showing");
});
于 2013-09-05T13:11:23.800 回答