创建一个jQuery插件,我该怎么做定制范围?
题
我想创建一个jQuery插件与API是这样的:
$("#chart").pluginName().attr("my_attr");
代替这些:
$("#chart").pluginName_attr("my_attr");
$.pluginName.attr("#chart", "my_attr");
基本上,而不必命名空间每次作用类似于那些在jQuery的方法,我想“范围”的方法,以一个定制的API,其中$("#chart).pluginName()
将返回的对象,使得get
,attr
,find
,和其他一些人将被完全重写。
我敢肯定,这不是一个很受欢迎的主意,因为它打破惯例(是吗?),但它更容易和更具可读性,而且可能更优化,比上述两个选项。你有什么想法?
解决方案
我尝试用的想法。
好像你可以只修改功能,该插件接收jQuery对象,并返回。
像这样:
$.fn.tester = function() { // The plugin
this.css = function() { // Modify the .css() method for this jQuery object
console.log(this.selector); // Now it just logs the selector
return this; // Return the modified object
}
return this; // Return the modified object
}
http://jsfiddle.net/EzzQL/1/ 的(从更新原覆盖的.html()为好)强>
$.fn.tester = function() {
this.css = function() {
console.log(this.selector); // This one logs the selector
return this;
}
this.html = function() {
alert(this.selector); // This one alerts the selector
return this;
}
return this;
};
// Because .css() and .html() are called after .tester(),
// they now adopt the new behavior, and still return a jQuery
// object with the rest of the methods in tact
$('#test1').tester().css().html().animate({opacity:.3});
// .css() and .html() still behave normally for this one
// that doesn't use the plugin
$('#test2').css('backgroundColor','blue').html('new value');
修改强>
另外,如果你要缓存,其应适用的自定义方法的元素,你可以在使用之前.apply()
的方法。
要对上述的例子中构建:
var $test1 = $('#test1'); // Cache the elements
$.fn.tester.apply($test1,[this]); // apply() the new methods
$test1.css().html().animate({opacity:.3}); // Use the new methods
不隶属于 StackOverflow