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

问题描述 投票:1回答:1

我们目前正在使用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>

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

wordpress wordpress-theming infinite-scroll
1个回答
1
投票

当你的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 must be unique to repeat the text from JavaScript.

解:

我们将使用WordPress提供一些帮助。 WordPress为您创建的所有帖子都有唯一的ID。

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

这将在每个帖子中附加文本。

© www.soinside.com 2019 - 2024. All rights reserved.