最近一直在忙dotnetnuke,没有时间来学点jQuery的东西,我真的是jQuery的超级fans,所以今天还是学点jQuery的东西并和大家分享一下。
以前我翻译过一个如何写jQuery插件的经典文章,这里再给出来一个相当好的,理论加例子的文章。
In case you want to share your plugin with others it can be a good idea to stick to the conventions of plugin authoring. Pick a suitable name like “myPlugin” and name your file jquery.myPlugin.js. Next thing is to define a function body.
(function($) {
$.fn.extend({
myPlugin: function() {
}
});
})(jQuery);
Wrapping everything inside an anonymous function and passing jQuery into it makes sure it doesn’t conflict with other libraries that uses ‘$’ as a shorthand (Don’t worry too much about this for now).
I’m going to call the first plugin “tabify”. The objective is to add some tabs to the following content.
Tab number one
Some tab content
Next tab
content...
Last tab
Even more stuff
Inside your plugin add the following:
return this.each(function() {
var obj = $(this);
});
An object passed through the plugin will now return a function. I also created a reference “obj” to the object currently inside the function. Add the following inside your “this.each” statement:
obj.click(function() { obj.css({ backgroundColor:"red"}); }); Now pass the desired object into the plugin: $(function(){{ $('#someContent').tabify(); });
Clicking #someContent should result in a red background. You could pass any object into the plugin. $(‘#someContent h2’) will set a red background to any “h2” within #someContent that is clicked.
Here’s the code for jquery.tabify with included comments. I’m hoping you’re fairly familiar with JavaScript / jQuery and its basic syntax.
(function($){
$.fn.extend({
tabify: function() {
return this.each(function() {
//Creating a reference to the object
var obj = $(this);
/* Create a reference for all headings and
it's content using .next().
Remember to pass the object reference
"obj" into the identifier. */
var headings = $('h2', obj);
var tabContent = headings.next();
//We wan't to hide the headings and the content
headings.hide();
tabContent.hide();
/* But we want to show content of the first
tab since it's selected by default. */
tabContent.eq(0).show();
//Prepend the object with the tab container (ul).
obj.prepend('');
//For every heading create an item (- )
headings.each(function() {
var label = $(this).text();
$("ul.tabs", obj).append("
- " + label + "
");
});
var tabs = $("ul.tabs li", obj);
//And add .sel class to first item
tabs.eq(0).addClass("sel");
//Create a reference to the tabs for each obj
var tabs = $("ul.tabs li", obj);
tabs.click(function() {
//When a tab is clicked "de-activate" the old one
tabs.removeClass("sel");
tabContent.hide();
$(this).addClass("sel");
//And display the clicked tab
var current = tabs.index($(this));
tabContent.eq(current).show();
});
});
}
});
})(jQuery);
You will also need some CSS to actually make your look like tabs.