【发布时间】:2021-02-28 16:33:24
【问题描述】:
我正在做一个测验项目。它需要修改 javascript 文件中的常量。
const questions=[
{
q:'where is the capital of India',
options:['New Delhi','Kolkatta','Varanashi','Agra'],
answer:1
},
{
q:'Who is the Prime Minister of India',
options:['Amit Shah','Narendra Modi','Rahul Gandhi','None of the above'],
answer:2
},
{
q:'where is the capital of India',
options:['New Delhi','Kolkatta','Varanashi','Agra'],
answer:1
}
]
但是我们需要在常量上添加 PHP。
试试这个,但是不行……
const questions=[
{
q:'<?php echo the_field("q_1"); ?>',
options:['(<?php echo the_field("option_1"); ?>)','(<?php echo the_field("option_2"); ?>)','(<?php echo the_field("option_3"); ?>)','(<?php echo the_field("option_4"); ?>)'],
answer:'<?php echo the_field("answer_1"); ?>'
},
{
q:'<?php echo the_field("q_2"); ?>',
options:['<?php echo the_field("option_1_2"); ?>','<?php echo the_field("option_2_2"); ?>','<?php echo the_field("option_3_2"); ?>','<?php echo the_field("option_4_2"); ?>'],
answer:'<?php echo the_field("answer_2"); ?>'
},
{
q:'<?php echo the_field("q_3"); ?>',
options:['<?php echo the_field("option_1_3"); ?>','<?php echo the_field("option_2_3"); ?>','<?php echo the_field("option_3_3"); ?>','<?php echo the_field("option_4_3"); ?>'],
answer:'<?php echo the_field("answer_3"); ?>'
}
]
【问题讨论】:
-
你能打印这个吗 let q1 = '';控制台.log(q1);上常数变量
-
我能知道'the_field'变量来自哪里吗?
-
如果您尝试在 JavaScript 文件中运行 php 代码..这是不可能的。 PHP 是一种服务器端语言……它需要预处理……但 JavaScript 在前端执行。
-
@DasunManathunga 使用 WordPress 插件 ACF。这不是一个大而复杂的代码。只需要用php替换文本即可。
-
如果它是一个 javascript 文件,那么不,您不能在其中放入 PHP 变量,因为该文件不会通过 PHP 处理器。你能做的最好的是将它放在 php 文件的脚本部分中,以便 javascript 可以选择它
标签: javascript php wordpress constants advanced-custom-fields