簡體   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