Jquery插件绑定ajax加载元素



这是我的jquery代码,它的工作。但是我有一个问题,如果ajax加载一个新的输入,这个输入不适合我的mylimit。如何解决这个问题?谢谢。

(function ( $ ) {
    $.fn.mylimit = function() { 
        return this.each(function(){
            var $this = $(this);
            if ($this.attr('limit_count') && $this.attr('message')) {
                var limit_count = $this.attr('limit_count');
                var message = $this.attr('message');
                $this.on('keyup', function(){
                    var count = $this.val().length;
                    if(count > limit_count) {
                        alert(message);
                    }
                });
            }
        });  
    };
    $('input').mylimit();
}( jQuery ));

JSFiddle: http://jsfiddle.net/lighter/BuaY4/16/

1)修复现有代码

您有许多输入错误(例如,limit-count不是您的属性之一,limit-message是一个)。count > limit中引用的一个变量是limit,但您将其称为limit_count:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/BuaY4/13/

(function ( $ ) {
    $.fn.mylimit = function() { 
        return this.each(function(){
            var $this = $(this);
            if ($this.attr('limit').length && $this.attr('limit-message').length) {
                var limit = $this.attr('limit');
                var message = $this.attr('limit-message');
                $this.on('keyup', function(){
                    var count = $this.val().length;
                    if(count > limit) {
                        alert(message);
                    }
                });
            }
        });  
    };
    $('input').mylimit();
}( jQuery ));

2。处理动态加载的内容:

你需要弄清楚如何引用一个还不存在的对象。您可以在Ajax加载后重新运行插件,或者使用委托事件处理程序(如果可能的话首选)。

JSFiddle: http://jsfiddle.net/TrueBlueAussie/BuaY4/18/

jQuery(function ($) {
    $(document).on("keyup", "input", function () {
        var $this = $(this);
        if ($this.attr('limit').length && $this.attr('limit-message').length) {
            var limit = $this.attr('limit');
            var message = $this.attr('limit-message');
            console.log("Limit: " + limit);
            var count = $this.val().length;
            if (count > limit) {
                alert(message);
            }
        }
    });
});

使用委托事件处理程序(on的特殊变体)。它监听事件冒气泡直到一个不变的祖先(document是默认的,如果你没有一个方便的),它然后应用jQuery过滤器,它然后调用函数为每个匹配的元素,导致事件

指出:

  • jQuery(function($){ YOUR CODE HERE });是一个特殊的快捷方式,它既是一个DOM就绪的事件处理程序,又为您提供了一个局部作用域的$变量。非常方便:)
  • 没有必要实现这个功能作为一个插件(例如作为$.fn.mylimit =),因为它不能应用于动态加载的内容(你所要求的)。只需包含代码,它将应用于所有具有您的属性的输入。

最新更新