jQuery.Click方法重新加载页面
我正在尝试创建一个浮动div,它会在触发按钮时显示出来。 这并不难,但是当我按下按钮时,页面会自动重新加载。 我不知道为什么。
我试图使用Bootstrap的Popover,但由于同样的问题它没有按预期工作。 当弹出窗口被触发时,页面重新加载并且弹出窗口明显消失。
我正在使用RoR,只是说如果找出问题会有用。
我在文档的底部有这样的东西:
Show $(document).ready(function() { console.log("Page is loaded."); // Custom Popover $("#example").click(function() { console.log("Showing"); }); });
页面加载时会显示第一个console.log
内部就绪function。 当我触发“Show”按钮时,该console.log
再次显示在浏览器的控制台中。 这没有任何意义。
谢谢!
您需要使用preventDefault()
来停止链接的默认行为:
$("#example").click(function(e) { e.preventDefault(); console.log("Showing"); });
你有问题,而不是你用过href
的class
Show
你有两个问题:
您在href
属性而不是类中设置class
Show
您需要在调用链接时阻止浏览器跟随href
:
$("#example").click(function( e ) { e.preventDefault(); // don't follow href console.log("Showing"); });
在这里你可以找到一个完整的例子。 在这里测试
$(document).ready(function() { console.log("Page is loaded."); $("#example").click(function(e) { e.preventDefault(); alert("works"); });
});
这不可能,它应该工作正常。 还有一些其他问题,请填写整页。
$(document).ready(function() { console.log("Page is loaded."); // Custom Popover $("#example").click(function() { console.log("Showing"); });
});
看这里
你必须停止锚点来执行它的默认function,加载指定其href的页面。 这段代码应该可以解决问题:
$("#example").click(function(event) { event.preventDefault(); console.log("Showing"); });