我正在使用WordPress和Polylang插件。
我正在尝试通过jQuery设置三个li
元素的文本内容。这不是问题。但是,当我需要使用PHP显示文本时,这成为一个问题。
jQuery(document).ready(function($){
$(".dot:nth-child(1)").text("<?php echo pll_e('String 1'); ?>");
$(".dot:nth-child(2)").text("String 2");
$(".dot:nth-child(3)").text("String 3");
});
有没有其他选择,还是我做错了什么?也许这甚至是不可能的。
大概你的JavaScript不在由PHP执行的扩展名为.php
的文件中。或者,pll_e('String 1');
返回一个带有"
(双引号)的字符串。
要解决任一问题,您可以执行以下操作(这既快速又脏)
// in a file called thejsfile.js
function foo(obj) {
jQuery(document).ready(function($) {
// you could consider running this as a loop
// $('.dot').each(function () { /* ... */ });
$(".dot:nth-child(1)").text(obj.str1);
$(".dot:nth-child(2)").text(obj.str2);
$(".dot:nth-child(3)").text(obj.str3);
});
}
在由 PHP 执行的文件中,输出作为 HTTP 响应发送。
<?php
$array = array(
'str1' => pll_e('String 1'),
'str2' => pll_e('String 2'),
'str3' => pll_e('String 3'),
);
$jsInitObj = json_encode($array);
?>
<script type="text/javascript" src="thejsfile.js"></script>
<script type="text/javascript">
(function(obj) {
foo(obj);
}(<?php echo $jsInitObj; ?>));
</script>
另一种选择是通过 AJAX 请求加载pll_e('String 1');
的值。
编辑:更新了答案以适应以下评论中的问题。
正如@JonathanCrowe所评论的那样;只要你在.php
文件中这样做,它就可以工作。我只是把它放在<script>
-tags内的footer.php
文件中。
<script type="text/javascript">
jQuery(document).ready(function($){
$(".dot:nth-child(1)").text("<?php echo pll_e('Om Os'); ?>");
$(".dot:nth-child(2)").text("<?php echo pll_e('OES-analyse'); ?>");
$(".dot:nth-child(3)").text("<?php echo pll_e('Malingsinspektion'); ?>");
$(".dot:nth-child(4)").text("<?php echo pll_e('Metallurgi'); ?>");
$(".dot:nth-child(5)").text("<?php echo pll_e('PMI test'); ?>");
$(".dot:nth-child(6)").text("<?php echo pll_e('Hårdhedsmåling'); ?>");
});
</script>