我们目前正在为博客文章使用Ajax无限滚动。但是我们希望在每个博客上都包含脚本(javascript)。所有的工作都很好,除了脚本只在博客顶部显示一次。
下面是为Ajax无限滚动标准修改的singles.php循环的片段:
<?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>
不知道为什么脚本只显示一次。当我把它放在每个博客标题的顶部时。
发布于 2018-04-02 11:57:07
当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为您创建的所有帖子都具有唯一的ids。
循环中的the_ID();方法返回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>这将在每一篇文章中附加文本。
https://stackoverflow.com/questions/49609942
复制相似问题