繁体   English   中英

在外部jQuery脚本中使用PHP

[英]Using PHP in External jQuery Script

事前,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()使用的概念相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM