在 Google 搜索结果中的所有链接都变成紫色并且我在几个小时内感到沮丧之后,我决定请你们帮助我解决这个问题。
在我的 WordPress 主页上,循环生成包含博客上所有帖子标题的列表。为了缩短网站加载时间,我决定使用 AJAX。您不必一次加载所有内容,而是单击某个帖子的标题以在下面显示其内容。简单地说,当您单击它时,会将帖子的 id(从属性标签获取)发布到 ajax.php 文件(带有循环显示内容的 WordPress 模板...)。当内容被读出时,它会显示在前端。
问题出在插件上。因为它们在内容加载(DOM 更改)后不会重新触发。显然,我不想要将安装的每个插件添加到 AJAX 回调的解决方案,因为它不是应该的方式。我想要它自动化。 WordPress 旨在简单且易于管理(即使从开发人员的角度来看也是如此)。
我已经尝试过 live()、livequery() - 插件、listen() - 插件..并尝试将我的 ajax 脚本更改为更像 WordPress 的方式(使用 admin-ajax.php)和每次结果是一样的 - 它不起作用。
我所说的插件是指例如:语法荧光笔、社交分享按钮或用于图像的 FancyBox/Lightbox...即使我将插件的功能添加到 ajax 循环中以手动显示它,它仍然会失败...
我怀疑我使用的 live() 函数可能有点错误或者其他什么......无论如何,这是我的代码:
前端循环(index.php)
<?php while (have_posts()) : the_post(); ?>
<article>
<div class="fake">
<div class="header" rel="<?php the_ID(); ?>">
<h1 class="title"><?php the_title(); ?></h1>
<span class="tags">
<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ', ';
}
}
?>
</span>
<span class="post_no">#<?=$published?></span>
<div class="arrow"></div>
</div>
</div>
<div class="content"></div>
</article>
<?php endwhile; ?>
我使用的 AJAX 片段:
$('.header').live('click',function() {
var content = $(this).parent().parent().find('.content');
var post_id = $(this).attr("rel");
content.load("http://localhost/simpleecode/ajax/",{id:post_id}).delay(800).slideDown('slow');});
带有 AJAX 循环的模板:
<?php $post = get_post($_POST['id']); ?>
<?php if ($post) : ?>
<?php setup_postdata($post); ?>
<?php the_content(); ?>
<?php endif;?>
我认为您可能也喜欢链接到开发网站来检查您自己的 DOM 和文件(我使用短链接,因为它是开发网站,无论如何我都不希望它公开):
希望您知道如何做到这一点:S
最佳答案
使用 AJAX 请求的成功/完成回调来调用 DOM 中新的 html 插件。
content.load("http://localhost/simpleecode/ajax/",{id:post_id}, function(){
/* new html now exists*/
$(this).find('.classThatNeedsPlugin').somePlugin();
}).delay(800).slideDown('slow');
<强> jQuery API - load() method docs
如果插件中有任何尺寸敏感的代码,您可能需要更改它以在动画回调中调用插件
编辑:不要使用delay()来设置动画,而是在同一个成功回调中调用动画,然后html就准备好了
content.load("http://localhost/simpleecode/ajax/",{id:post_id}, function(){
/* new html now exists*/
$(this).find('.classThatNeedsPlugin').somePlugin().slideDown('slow');
});
Edit2 替代方法:jQuery 延迟对象方法。
您还可以使用 deferred 来设置 ajax 回调。
var jqXhr= content.load("http://localhost/simpleecode/ajax/",{id:post_id});
$.when( jqXhr).then( /* plugin function */);
或自定义事件
/* on page load*/
$('#myTable').on('myCustomEventName', function(){
$(this).doPlugins();
}).trigger('myCustomEventName');
/* ajax callback*/
content.load("http://localhost/simpleecode/ajax/",{id:post_id}, function(){
$('#myTable').trigger('myCustomEventName')
})
关于jquery - WordPress中ajax加载页面后如何触发jquery插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171264/