我正在使用 Wordpress,我的目标是创建一种 main.js
要调用的文件,而不是包含在我的脚本页面中。作为一个插件,我需要在其中使用一些 php 变量和函数。
我可以像这样编写我的 .js
<?php
$dd = get_option('KleeiaDev_project_period');
if(empty($dd)) $dd = 7; ?>
var myDate=new Date();
myDate.setDate(myDate.getDate()+<?php echo $dd; ?>);
$(document).ready(function() {
$('#ending').datepicker({
showSecond: false,
timeFormat: 'hh:mm:ss',
currentText: '<?php _e('Now','KleeiaDev'); ?>',
closeText: '<?php _e('Done','KleeiaDev'); ?>',
ampm: false,
dateFormat: 'dd-mm-yy',
timeFormat: 'hh:mm tt',
timeSuffix: '',
maxDateTime: myDate,
timeOnlyTitle: '<?php _e('Choose Time','KleeiaDev'); ?>',
timeText: '<?php _e('Time','KleeiaDev'); ?>',
hourText: '<?php _e('Hour','KleeiaDev'); ?>',
minuteText: '<?php _e('Minute','KleeiaDev'); ?>',
secondText: '<?php _e('Second','KleeiaDev'); ?>',
timezoneText: '<?php _e('Time Zone','KleeiaDev'); ?>'
});
});
或者我应该考虑一些事情?我的意思是这可能吗?现在这段代码和更多代码直接在我的 php 插件文件中。 谢谢。
最佳答案
如果您想发送 php 变量到外部 js 文件,您需要执行以下操作:
在 .php 文件内
<?php
// Variables
$var1 = "test1";
$var2 = "test2";
?>
// Include your js file
<script type="text/JavaScript" src="/js/main.js"></script>
// Send your php variables to js variables; this has shorthand php tags also.
<script type="text/javascript">
var var1 = "<?= $var1 ?>";
var var2 = "<?= $var2 ?>";
</script>
然后在你的js文件中你可以调用这些变量:
main.js
$(document).ready(function() {
alert(var1); //Alerts 'test1'
alert(var2); //Alerts 'test2'
});
关于javascript - 我可以调用内部包含 php 的外部 jQuery 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163234/