javascript - 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>
解决方案
- 您需要先设置该值,以便稍后获取!在线
6
你需要设置它。 - 在您的回调函数中替换
return
为。echo
- 您需要
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]');
推荐阅读
- amazon-web-services - 使用 AWS Lambda 函数 (Java) 将文件上传到 s3
- httpresponse - AWS API Gateway - 方法响应中没有模型选项
- vba - 从 sheet1 列 A、B、C、G、F、R、S、T 复制到列 A、B、C、D、E、F、G、H 中的表 2
- c++ - 如何在类空间中给成员函数起别名?
- postgresql - 如何在 postgreSQL 中对查询性能进行基准测试?CPU 或 TIME,但每次运行都需要保持一致
- python - 在 openPyXl 中打开 13mb 文件使用 1.2 gb 内存
- vimeo - 当调用“apiready”事件时,无法访问视频的持续时间。
- python - python 机械化 400 错误请求
- javascript - Jquery 数据表导出到 Excel,想要将一些数字列转换为字符串
- python - 正则括号 Python 的非捕获版本