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

plugins - jQuery Click event is not fired at all

programmeradmin3浏览0评论

I'm trying to make a widget plugin that allows user to upload image. but I have a problem in jQuery events that it is never happen !

includes/myplugin.scripts

function media_uploader_enqueue() {
    wp_enqueue_media();
    wp_register_script('media-uploader', plugins_url().'/simple-plugin/js/main.js',array('jquery'),null, true);
    wp_enqueue_script('media-uploader');
}
add_action('admin_enqueue_scripts', 'media_uploader_enqueue');

js/main.js

jQuery(document).ready(function ($) {
    console.log($('#xyz')); // works !

    $('#xyz').click(function (e) {
        e.preventDefault();
        console.log("in click event");  // never happens !!
    })

})


I'm trying to make a widget plugin that allows user to upload image. but I have a problem in jQuery events that it is never happen !

includes/myplugin.scripts

function media_uploader_enqueue() {
    wp_enqueue_media();
    wp_register_script('media-uploader', plugins_url().'/simple-plugin/js/main.js',array('jquery'),null, true);
    wp_enqueue_script('media-uploader');
}
add_action('admin_enqueue_scripts', 'media_uploader_enqueue');

js/main.js

jQuery(document).ready(function ($) {
    console.log($('#xyz')); // works !

    $('#xyz').click(function (e) {
        e.preventDefault();
        console.log("in click event");  // never happens !!
    })

})


Share Improve this question asked Jul 20, 2020 at 12:25 Islam Hanafi MahmoudIslam Hanafi Mahmoud 1616 bronze badges 2
  • 2 This seems like it's specifically a jquery question about how to fire your jquery event, so as it's not related to Wordpress it might do better on a Web Development stackexchange, or StackOverflow. If you leave the question here you might want to add the HTML of the xyz element too – mozboz Commented Jul 20, 2020 at 13:00
  • 1 I found the answer and I think this is related to wordpress, thought, thanks for your suggestion @mozboz – Islam Hanafi Mahmoud Commented Jul 20, 2020 at 13:16
Add a comment  | 

1 Answer 1

Reset to default 3

I Found the answer for my question , And I'm sharing it here in case anyone interested.

the problem was that click event won't work on dynamically generated html elements

and the alternative that worked is using on

$('body').on('click','#elementID',Callback)
发布评论

评论列表(0)

  1. 暂无评论