首页 > jquery的插件问题

jquery的插件问题

<p data-x="one">Text one</p>
<p data-x="two">Text two</p>
<p data-x="three">Text three</p>
<p data-x="four">Text four</p>
(function($) {
    $.fn.highlite = function(options) {
        this.css({
            "background": "yellow"
        });
        return this;
    };
})(jQuery);

(function($) {
    $.fn.makeRed = function(options) {
        this.css({
            "color": "red"
        });
        return this;
    };
})(jQuery);

(function($) {
    $.fn.mangle = function(options) {
        this.append(' - ' + this.data('x'));
        return this;
    };
})(jQuery);

$(document).ready(function() {
    $('p').highlite().makeRed().mangle();
});

链接在这:http://jsfiddle.net/ambiguous/eyHeu/
理想中的highlite(),makeRed()这两个方法是对的。
为什么mangle()是不对的!

我看着像没用闭包引起的问题,因为没用闭包的时候会出现这种问题。


那是因为你返回的是 this 而不是 this.each(function(){}) 因此没把分进行链式调用。

(function($) {
    $.fn.highlite = function(options) {      
        var $this=$(this);
        return $this.each(function(){             
            $this.css({
            "background": "yellow"
        });
        });
    };
})(jQuery);

(function($) {
    $.fn.makeRed = function(options) {      
        var $this=$(this);
        return $this.each(function(){         
            $this.css({
            "color": "red"
        });
        });
    };
})(jQuery);

(function($) {
    $.fn.mangle = function(options) {        
        var $this=$(this);
        return $this.each(function(){            
            $this.append(' - ' + $this.data('x'));
        });
    };
})(jQuery);

$(document).ready(function() {
    $('p').highlite().makeRed().mangle();
});

正确姿势: 用$(this).each包住你的操作

【热门文章】
【热门文章】