首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在无限滚动的Wordpress文章中包含脚本

在无限滚动的Wordpress文章中包含脚本
EN

Stack Overflow用户
提问于 2018-04-02 10:57:06
回答 1查看 112关注 0票数 1

我们目前正在为博客文章使用Ajax无限滚动。但是我们希望在每个博客上都包含脚本(javascript)。所有的工作都很好,除了脚本只在博客顶部显示一次。

下面是为Ajax无限滚动标准修改的singles.php循环的片段:

代码语言:javascript
运行
复制
<?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; ?>

下面是中继器模板的片段,其中包括一个简单的脚本代码。

代码语言:javascript
运行
复制
<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>

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-02 11:57:07

当ajax请求中继器模板时,document.write()将对document.open()进行间接调用,以打开新的输出流。下次滚动更多时,write()方法将无法工作,因为前面的输出流当前是打开的。你应该关闭溪流。

你可以试试这个方法:

代码语言:javascript
运行
复制
document.open();
document.write("This text is displayed using a simple javascript.");
document.close();

document.write()是一个不好的生产实践。你只应该用它来测试。

更好的解决办法:

代码语言:javascript
运行
复制
<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获取元素来追加文本。

代码语言:javascript
运行
复制
<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>

这将在每一篇文章中附加文本。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49609942

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档