在无限滚动 Wordpress 帖子中包含脚本

Include script in infinite scroll Wordpress Posts

我们目前正在对博文使用 Ajax 无限滚动。但我们希望在每篇博文中包含脚本 (javascript)。一切正常,除了脚本只在博文的最顶部显示一次。

这里是 singles.php 循环的代码片段,已针对 Ajax 无限滚动标准进行了修改:

<?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>

不确定为什么脚本只显示一次。当我把它放在每篇博文标题的顶部时。

当您的 ajax 请求转发器模板时,

document.write() 将间接调用 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 对您创建的所有 post 都有唯一的 ID。

the_ID(); WordPress 中的方法 While 循环 returns post 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>

这将在每个 post 中附加文本。