我们当前正在使用Ajax Infinite Scroll进行博客文章。但是我们想在每个博客文章中包括脚本(JavaScript(。一切正常,除了脚本仅在Blogpost的最高部分显示一次。
。这是singles.php循环的片段,已针对Ajax Infinite滚动标准进行了修改:
<?php while ( have_posts() ) : the_post(); ?>
<?php if (et_get_option('divi_integration_single_top') <> '' && et_get_option('divi_integrate_singletop_enable') == 'on') echo(et_get_option('divi_integration_single_top')); ?>
<?php
echo do_shortcode('[ajax_load_more cache="true" cache_id="2869844236" cta="true" cta_position="after:1" css_classes="call-to-actions call-to-actions-js" images_loaded="true" post_type="post" repeater="default" previous_post="true" previous_post_id="'. get_the_ID() .'" posts_per_page="1" button_label="Previous Post"]');
?>
<?php endwhile; ?>
这是中继器模板的片段,其中包括一个简单的脚本代码。
<article id="post-<?php the_ID(); ?>" <?php post_class( 'et_pb_post' ); ?>>
<script>
document.write("This text is displayed using a simple javascript.");
</script>
<div class="et_post_meta_wrapper">
<h1><?php the_title(); ?></h1>
<?php the_post_thumbnail('hero', array('alt' => get_the_title())); ?>
</div>
<div class="entry-content">
<?php
do_action( 'et_before_content' );
the_content();
wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'Divi' ), 'after' => '</div>' ) );
?>
</div>
</article>
不确定为什么脚本只显示一次。当我将其放在每个博客文章的标题顶部时。
document.write()
将在您的AJAX请求Repeater模板时向document.open()
进行间接调用,以打开新的输出流。下次您滚动更多时,write()
方法不起作用,因为先前的输出流当前打开。您应该关闭流。
您可以这样尝试:
document.open();
document.write("This text is displayed using a simple javascript.");
document.close();
document.write((是生产不良的做法。您只能将其用于测试。
更好的解决方案:
<p id="output"></p>
<script>
document.getElementById("output").innerHTML = "This text is displayed using a simple javascript.";
</script>
编辑:
每次完成AJAX请求完成时,我们将需要一个唯一的ID将文本附加到元素上。
在我上面的建议中
id必须是唯一的才能重复JavaScript的文本。解决方案:
我们将使用WordPress来帮助您。WordPress具有您创建的所有帖子的唯一ID。
the_ID();
wordpress内部的方法时,循环返回帖子ID。因此,在我们的P
元素中附加相同的ID,并通过通过其新ID获取该元素来附加文本。
<p id="output-<?php the_ID(); ?>"></p>
<script>
var idname = document.getElementById("output-<?php the_ID(); ?>");
idname.innerHTML = "This text is displayed using a simple javascript.";
</script>
这将在每个帖子中附加文本。