You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress如何使用shortcode获取localStorage值并正常展示

故障根因
  • 原有JS逻辑仅将strong标签内的数值赋值给了临时变量getnum,未执行localStorage.setItem('getnum', getnum)写入操作,读取localStorage自然返回空值
  • 短代码返回的script执行时机早于jQuery的DOM就绪回调,存在先读、后写的时序问题
  • document.write在DOM加载完成后执行会清空整个页面内容,属于废弃用法
修复代码

推荐直接通过DOM操作插入数值,无需绕localStorage,逻辑更稳定:

<?php
// 注册短代码,输出占位标签
function points_show_function() {
    return '<span class="show-points-placeholder"></span>';
}
add_shortcode('showpoints', 'points_show_function');

// 页脚注入JS逻辑,确保DOM加载完成后执行
add_action('wp_footer', function () {
?>
<script>
jQuery(document).ready(function ($) {
    // 提取积分数值
    const points = $('div.elementor-widget-container p > strong').text().trim();
    // 写入所有短代码占位位置
    $('.show-points-placeholder').text(points);
    // 若确实需要存储到localStorage可打开下一行注释
    // localStorage.setItem('getnum', points);
});
</script>
<?php
});

如果坚持使用localStorage的实现方式,补全写入逻辑+调整执行顺序即可:

<?php
function points_show_function() {
    // 等DOM就绪后再读取插入,避免时序问题
    return '<span class="show-points-placeholder"></span>
    <script>
    jQuery(document).ready(function ($) {
        $(".show-points-placeholder").text(localStorage.getItem("getnum"));
    });
    </script>';
}
add_shortcode('showpoints', 'points_show_function');

add_action('wp_footer', function () {
?>
<script>
jQuery(document).ready(function ($) {
    const getnum = $('div.elementor-widget-container p > strong').text().trim();
    // 补全localStorage写入逻辑
    localStorage.setItem('getnum', getnum);
});
</script>
<?php
});

内容的提问来源于stack exchange,提问作者namari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 22:09:00