最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Run JS function when JQ enqueued

programmeradmin4浏览0评论

I would like to run a javascript function when jQuery is ready. This doesn't work:

wp_enqueue_script('jquery');
?>
<script>
    (function() {
        doJQstuff()
    })();
</script>

Any ideas?

wp_localize_script( 'search-ajax', 'search_ajax_object',
    array( 
        'url' => admin_url( 'admin-ajax.php' ),
    )
);
wp_enqueue_script( 'search-ajax', get_template_directory_uri() . '/js/search-ajax.js', array('jquery'), null, true );

search-ajax.js

console.log(search_ajax_object) //-> Uncaught ReferenceError: search_ajax_object is not defined

I would like to run a javascript function when jQuery is ready. This doesn't work:

wp_enqueue_script('jquery');
?>
<script>
    (function() {
        doJQstuff()
    })();
</script>

Any ideas?

wp_localize_script( 'search-ajax', 'search_ajax_object',
    array( 
        'url' => admin_url( 'admin-ajax.php' ),
    )
);
wp_enqueue_script( 'search-ajax', get_template_directory_uri() . '/js/search-ajax.js', array('jquery'), null, true );

search-ajax.js

console.log(search_ajax_object) //-> Uncaught ReferenceError: search_ajax_object is not defined
Share Improve this question edited Jan 27, 2022 at 14:03 Fluxian asked Jan 27, 2022 at 12:27 FluxianFluxian 1809 bronze badges 7
  • You should load your script via wp_enqueue_script() as well, not output it directly in the template. Have you tried that? – kero Commented Jan 27, 2022 at 12:44
  • @kero Can you enqueue javascript functions that use php calls inside of the function body? – Fluxian Commented Jan 27, 2022 at 12:56
  • No, that is usually bad practice. Either use wp_localize_script() to pass data from PHP to JS or query the REST/ajax endpoints from JS. – kero Commented Jan 27, 2022 at 13:05
  • @kero I can't get that to work. Can you check the updated question and see what's wrong? :D The object is not accessible from the javascript – Fluxian Commented Jan 27, 2022 at 14:04
  • 1 @kero Ah, yeah that works. – Fluxian Commented Jan 27, 2022 at 14:10
 |  Show 2 more comments

1 Answer 1

Reset to default 1

You can't do that way

first you need to enqueue your script using :

wp_enqueue_script('jquery');
wp_enqueue_script('ns-likes-dislikes-for-posts-js', plugin_dir_url(__FILE__). 'path/to/your/js/file/from/plugin/directory/custom.js', array('jquery'), '1.0', true);

in custom js start writing your js with jquery but you can't use $, instead use jQuery.

if you want to use $ instead of jQuery try this code:

(function($){
  // enjoy jquery with $('selector')
})(jQuery)

first you need to enqueue script then you can localize it.

wp_enqueue_script( 'search-ajax', get_template_directory_uri() . '/js/search-ajax.js', array('jquery'), null, true );
wp_localize_script( 'search-ajax', 'search_ajax_object',
    array( 
        'url' => admin_url( 'admin-ajax.php' ),
    )
);
发布评论

评论列表(0)

  1. 暂无评论