我正在使用此代码:
$('div.x').find('#y').live('click', function(e) {
var aa = $(this);
if (aa.find('a').length == 0) {
aa.find('div.z').hide();
aa.find('input:submit').click(function(e) {
//...................
});
aa.append('xxx');
$('html, body').animate({ scrollTop: 100 });
}
e.preventDefault();
});
$('body').click(function(e) {
$('div.tt').slideUp('slow');
});
$('div.uu').delegate('div.gg', 'click', function(e) {
e.stopPropagation();
});
现在我想将上面的代码放到jQuery插件中。你能告诉我怎么做的吗?如何从外部接受默认值,以便可以从外部获取div类而不是在插件中保留硬编码?
答案 0 :(得分:1)
您可以使用此功能,只需更改一些内容:
https://github.com/OscarGodson/jQuery-Plugin-Skeleton
这是未经测试的,但我相信它应该有效:
/*
Copyright (c) <Year> <First & Last Name>, <Your Web Site>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function($){
$.fn.pluginname = function(options) {
var settings = $.extend({}, $.fn.pluginname.defaultOptions, options);
return this.each(function() {
var $this = $(this);
$this.find('#y').live('click', function(e) {
var aa = $(this);
if (aa.find('a').length == 0) {
aa.find('div.z').hide();
aa.find('input:submit').click(function(e) {
//...................
});
aa.append('xxx');
$('html, body').animate({ scrollTop: 100 });
}
e.preventDefault();
});
$('body').click(function(e) {
$('div.tt').slideUp('slow');
});
$('div.uu').delegate('div.gg', 'click', function(e) {
e.stopPropagation();
});
});
};
$.fn.pluginname.defaultOptions = {
};
})(jQuery);
你可以这样使用它:
$('div.x').pluginname();