首页 > 解决方案 > Wordpress 如何使用简码从 localStorage 获取值

问题描述

问题:
我需要创建一个包含从强标签中提取的值的简码。
当我回显“document.write(localStorage.getItem('getnum'));”;
代码显示值 85。
但是当我返回它(以下代码)时,短代码 [showpoints] 没有显示任何值。
请告诉我如何返回值?

我试过的代码:

    <?php
         ?>
    <script type="text/javascript">
      jQuery(document).ready(function($) {
        let getnum = $('div.elementor-widget-container p > strong').text();
        JSON.parse(localStorage.getItem('getnum'));
      });
    </script>

    <?php
    function points_show_function() {
    return "<script>document.write(localStorage.getItem('getnum'));</script>";
    }
    add_shortcode('showpoints', 'points_show_function');

控制台:
没有错误

HTML(代码来自 yith 积分和奖励插件):

<div class="elementor-element elementor-element-c1d0790 elementor-widget elementor-widget-text-editor" data-id="c1d0790" data-element_type="widget" id="pointsid" data-widget_type="text-editor.default">
    <div class="elementor-widget-container">
        <p>Your credit is  <strong>85</strong> Points</p>                       
    </div>
</div>

标签: javascriptphpjquerywordpressshortcode

解决方案


  1. 您需要先设置该值,以便稍后获取!在线6你需要设置它。
  2. 在您的回调函数中替换return为。echo
  3. 您需要do_shortcode在模板中使用来调用您的短代码!

所以你的代码会是这样的:

<script type="text/javascript">
  jQuery(document).ready(function($) {
    let getnum = $('div.elementor-widget-container p > strong').text();
    localStorage.setItem('getnum', getnum);
  });
</script>

<?php
add_shortcode('showpoints', 'points_show_function');

function points_show_function()
{
  echo "<script>document.write(localStorage.getItem('getnum'));</script>";
}

do_shortcode('[showpoints]');

do_shortcode('[showpoints]');将在这里发挥作用!所以把它放在你想要输出值的模板上。


替代方式

根据Mozilla Docs,您不需要使用JSON.stringify将单个字符串值设置为localStorage,但以防万一您无法使第一种方法起作用,请改用以下代码:

<script type="text/javascript">
  jQuery(document).ready(function($) {
    let getnum = $('div.elementor-widget-container p > strong').text();
    localStorage.setItem('getnum', JSON.stringify(getnum));
  });
</script>

<?php
add_shortcode('showpoints', 'points_show_function');

function points_show_function()
{
  echo "<script>document.write(JSON.parse(localStorage.getItem('getnum')));</script>";
}

do_shortcode('[showpoints]');

另一种使用方式return

如果您需要return回调函数中的值,请使用以下代码:

<script type="text/javascript">
  jQuery(document).ready(function($) {
    let getnum = $('div.elementor-widget-container p > strong').text();
    localStorage.setItem('getnum', JSON.stringify(getnum));
  });
</script>

<?php
add_shortcode('showpoints', 'points_show_function');

function points_show_function()
{
  return "<script>document.write(JSON.parse(localStorage.getItem('getnum')));</script>";
}

echo do_shortcode('[showpoints]');

推荐阅读