事前,JS不是我的强项。
我有一个外部.js文件,其中包含Smoove.JS的初始化信息。该文件正在WordPress插件中使用。我插入了一些PHP,以过滤传递给jQuery的参数。原始文件(smoove-init.js)被重命名为smoove-init.php。当我查看页面源代码时,一切看起来都很不错,但实际上没有任何反应。但是,该脚本在转换为PHP之前运行良好。我真的很感谢一些建议。
谢谢!
更新:
非常感谢@brasofilo的提示。对于任何有兴趣的人,我用来完成此工作的最终代码是:
/**
* 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
jQuery(window).load(function () {
jQuery( my_smoove ).smoove({
offset : '10%',
moveX : '-200px',
moveY : '0',
});
});
无需重命名JS,而是在头部打印JS变量并在里面使用它smoove-init.js
。像(未经测试的)之类的东西:
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
并在.js
文件内:
$( my_smoove ).smoove({/*etc*/});
这是使用相同的概念wp_localize_script()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句