繁体   English   中英

将JavaScript排入Wordpress插件

[英]Enqueue JavaScript into Wordpress plugin

- 我想在我的插件中包含JavaScript文件。 为了测试我正在调用JavaScript函数fun()。

- 我的插件目录结构是:

(first-plugin,(js,'animate.js'),'first_plugin.php')

上面给出的目录格式是这样的(dirname,content_in_the_dir_separated_by_comma)。

- 这是我的主要插件文件代码:

function wl_include_files() {
    wp_enqueue_script('wl_js', plugin_dir_path( __FILE__ ) . '/js/animate.js', array( 'jquery' ));
}

function wl_activate_plugin() {
    add_action('admin_enqueue_scripts', 'wl_include_files');
}

//
register_activation_hook(__FILE__, 'wl_activate_plugin');

function test() {
    $v = "<script>fun();</script>";
    echo $v;
}

//
add_action('admin_init', 'test');

- 这是我的JavaScript文件代码:

console.log('hi, file included properly.');

function fun() {
    alert("Hey, Someone calling me.");
}

- 我的控制台出现以下错误:

ReferenceError:未定义fun

- 任何人都可以说出问题是什么?

当用户访问管理区域时,在任何其他挂钩之前触发admin_init()挂钩。 这意味着在构造页面的任何部分之前调用test() 或者换句话说,在<head>包含animate.js之前,甚至在<html>标签之前调用fun()并且更多地调用。

test.php(测试插件目录下的主插件文件)

//this wp_footer hook is called once the entire front-end page body has been constructed
add_action('wp_footer', 'test');

wp_enqueue_script( 'myjs', plugin_dir_url( __FILE__ ) . '/js.js');

function test()
{
    echo '<script>test();</script>';
}

js.js(在同一测试目录中)

function test()
{
    console.log("Function called.");
}

(function ()
{
    console.log('JavaScript successfully included.');
})();

更多链接:

暂无
暂无

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

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