[英]jQuery.Click method reloads the page
I'm trying to creating a floating div who shows up when a button is triggered. 我正在尝试创建一个浮动div,当按钮被触发时它会出现。 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. 我试图使用Bootstrap的Popover,但由于同样的问题它没有按预期工作。 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. 我正在使用RoR,只是说如果找出问题会有用。
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. 页面加载时会显示第一个console.log
内部就绪功能。 When I trigger the button "Show", that console.log
is again shown in browser's console. 当我触发“Show”按钮时,该console.log
再次显示在浏览器的控制台中。 And that doesn't make any sense. 这没有任何意义。
Thanks! 谢谢!
You need to stop the default behaviour of the link by using preventDefault()
: 您需要使用preventDefault()
来停止链接的默认行为:
$("#example").click(function(e) {
e.preventDefault();
console.log("Showing");
});
你有问题,而不是你用过href
的class
<a href="#" class="btn btn-small btn-warning" id="example">Show</a>
You have two issues: 你有两个问题:
You're setting your classes in your href
attribute instead of class
您在href
属性而不是类中设置class
<a href="#" class="btn btn-small btn-warning" id="example">Show</a>
You'll want to stop your browser from following the href
when the link is invoked: 您需要在调用链接时阻止浏览器跟踪href
:
$("#example").click(function( e ) {
e.preventDefault(); // don't follow href
console.log("Showing");
});
you have to stop the anchor to do it's default function, loading the page specified its href. 你必须停止锚点来执行它的默认功能,加载指定其href的页面。 This code should do the trick: 这段代码可以解决这个问题:
$("#example").click(function(event) {
event.preventDefault();
console.log("Showing");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.