【发布时间】:2015-08-06 16:14:31
【问题描述】:
我正在尝试使用 Ajax 和 jQuery 构建 Wordpress 主题。每当在首页上单击指向帖子的链接时,该帖子就会在首页上的 div#single-post-container 中加载。我实现了这个复制Stan Kostadinovmethod:
jQuery 看起来像这样:
jQuery(document).ready(function($){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_link = $(this).attr("href");
$("#single-post-container").removeClass("hidden");
$("#single-post-container").html("");
$("#single-post-container").load(post_link, function() {
$(".close").click(function(){
$("#single-post-container").addClass("hidden");
});
});
$('body').scrollTop(0);
return false;
});
});
在正在加载的帖子内容中,我有默认的 Wordpress 帖子导航,它为我提供了以下 html:
<div class="nav-links">
<div class="nav-previous"><a href="link-to-previous-post" rel="prev"><span>link</span></a></div>
<div class="nav-next"><a href="link-to-next-post" rel="next"><span>Link</span></a></div></div>
我想要的是,每当单击下一个或上一个帖子链接以覆盖默认行为时,它会在新页面中打开帖子并相应地在同一 div#single-post-container 中动态加载/替换内容头版。
我已经尝试将它添加到我的 jQuery 中:
$(".nav-previous a").click(function () {
var post_nav = $(this).attr("href");
$( "#single-post-container" ).empty();
$("#single-post-container").removeClass("hidden");
$("#single-post-container").load(post_nav, function() {
$(".close").click(function(){
$("#single-post-container").addClass("hidden");
});
});
$('body').scrollTop(0);
return false;
});
没有运气。我尝试通过添加来防止默认行为:
e.preventDefault();
这也不起作用。我是 jQuery 的新手,所以请多多包涵……我正在本地开发,所以我无法向您展示实际操作。对于这方面的任何帮助,我将不胜感激。
如果您需要我澄清,请告诉我。
谢谢。
【问题讨论】:
-
preventDefault 应该是这样的。你是这样添加的吗? $(".nav-previous a").click(function (e) {e.preventDefault(); 也使 $(".nav-previous a").click(function () { this 变为 "$("。 nav-previous a").on("click",function () {"
-
您好 Farhan,感谢您对我的问题感兴趣。正如您所建议的那样,我刚刚尝试过: $(".nav-previous a").on("click",function (e) { e.preventDefault(); 它仍在新页面中打开帖子。它似乎 preventDefault 位没有做任何事情。
-
你也试过 $(".nav-previous a").on("click",function (e) {e.preventDefault();
-
是的,这就是我刚刚尝试过的。
-
有机会演示吗?
标签: jquery ajax wordpress navigation