[英]Using PHP in External jQuery Script
In advance, JS isn't my strong suit. 事前,JS不是我的强项。
I have an external .js file containing the initializing info for Smoove.JS. 我有一个外部.js文件,其中包含Smoove.JS的初始化信息。 This file is being used in a WordPress plugin. 此文件正在WordPress插件中使用。 I inserted some PHP to allow for filtering the parameters passed into the jQuery. 我插入了一些PHP,以过滤传递给jQuery的参数。 The original file (smoove-init.js) was renamed to smoove-init.php. 原始文件(smoove-init.js)重命名为smoove-init.php。 Everything looks good when I view the page source but nothing is actually happening. 当我查看页面源代码时,一切看起来都不错,但实际上没有任何反应。 However, the script worked fine before converting to PHP. 但是,该脚本在转换为PHP之前运行良好。 I'd really appreciate some advice. 我真的很感谢一些建议。
Thanks! 谢谢!
UPDATE: 更新:
Big thanks to @brasofilo for his tip. 非常感谢@brasofilo的提示。 For anyone interested, the final code I used to get this working is: 对于任何感兴趣的人,我用来完成此工作的最终代码是:
/**
* Outputs filtered selectors to the Smoove.js script.
*
* Assigns default values to $args and checks to see if they're being filtered.
* Adds the default/filtered selectors to a JS variable and outputs to wp_head.
* Applies the .smoove() to the variable.
*
* @param array $args Array of selectors to which .smoove() applies.
* @param string $selectors The string value of the $args array separated by commas.
*/
add_action( 'wp_head', 'run_smoove', 0 );
function run_smoove() {
$args = array( 'img' );
if ( has_filter( 'filter_smoove_args' ) ) {
$args = apply_filters( 'filter_smoove_args', $args );
}
$selectors = implode( ', ', $args );
?>
<script type="text/javascript">
var my_smoove = '<?php echo $selectors; ?>';
</script>
<?php
}
smoove-init.js smoove-init.js
jQuery(window).load(function () {
jQuery( my_smoove ).smoove({
offset : '10%',
moveX : '-200px',
moveY : '0',
});
});
Instead of renaming your JS, print a JS variable at the head and use it inside smoove-init.js
. 不用重命名JS,而是在头部打印JS变量,然后在smoove-init.js
使用它。 Something like (untested): 像(未经测试的):
add_action( 'wp_head', function() { // conditional tags can be used here: codex.wordpress.org/Conditional_Tags
$args = array( 'img', '.widget' );
if ( has_filter( 'smoove_args' ) ) {
$args = apply_filters( 'smoove_args', $args );
}
$return = implode( ', ', $args );
?>
<script type="text/javascript">
var my_smoove = '<?php echo $return; ?>';
</script>
<?php
}, 0 ); // priority 0, first to print
And inside the .js
file: 在.js
文件中:
$( my_smoove ).smoove({/*etc*/});
This is the same concept that wp_localize_script()
uses. 这与wp_localize_script()
使用的概念相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.