問題:
我需要創建一個包含從強標簽中提取的值的簡碼。
當我回顯 "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>
uj5u.com熱心網友回復:
- 您需要先設定該值,以便以后可以獲取它!
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]');
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/325538.html
標籤:javascript php 查询 WordPress的 短代码
