【问题标题】:jQuery plugin - dynamic click handling on global selectorjQuery 插件 - 全局选择器上的动态点击处理
【发布时间】:2017-05-02 11:48:22
【问题描述】:

我正在编写一个 jQuery 插件,它加载一个小部件(GET 方法),稍后应该触发一个点击事件。

初始化插件时元素选择器不在 DOM 中。那么如何实现选择器的全局存储来处理点击事件呢?

我使代码简短易懂。

(function($) {
    var $template; // the global variable

    $.fn.myPlugin = function() {
        $(this).bind('click', function(e) {
            $.get('/template.html', function(data) {
                $('body').append(data);
                $template = $(data); // set global variable here
            }
        }

        // fire click event on global variable here, but $template is undefined
        $(document).on('click', $template.find('.button'), function() {
            // do something
        }
    }
})(jQuery);

谢谢!

【问题讨论】:

    标签: jquery plugins jquery-plugins scope global-variables


    【解决方案1】:

    当模板确定已经加载时,只需在回调中定义事件处理程序即可。

    (function($) {
        var $template; // the global variable
    
        $.fn.myPlugin = function() {
            $(this).bind('click', function(e) {
                $.get('/template.html', function(data) {
                    $('body').append(data);
                    $template = $(data); // set global variable here
                    // fire click event on global variable here, but $template is undefined
                    $(document).on('click', $template.find('.button'), function() {
                    // do something
                    }
                }
            }
        }
    })(jQuery);
    

    【讨论】:

    • 我已经考虑过了,但没有其他方法可以让我稍后使用选择器吗?无论如何感谢您的帮助!
    • 如果您真的不想将处理程序放在该块中,可以使用Promise 进行提取,然后使用.then() 初始化处理程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多