如何创建简单的jQuery插件? [英] How to create simple jQuery plugin?
本文介绍了如何创建简单的jQuery插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个测试插件应该像这样工作:单击一个元素时,它会向下移动。就那么简单。
This test plugin, is supposed to work like this: When an element is clicked, it moves down. Simple as that.
jQuery.fn.moveDown = function(howMuch){
$(this).css("border", "1px solid black");
$(this).click(function(){
$(this).css("position", "relative");
$(this).animate({top: '+='+howMuch});
});
}
问题是,当点击一个元素时,它不仅会移动点击的元素元素以及插件所应用的所有其他元素。
The problem is, when an element is clicked, it not only moves the clicked element but also ALL the other elements which the plugin was applied to.
这是什么解决方案?
推荐答案
对于插件创作尝试这种方式,更加可靠:
For plugin authoring try this way, much more solid:
编辑:
这里有jsFiddle示例。
PLUGIN:
(function($){
$.fn.extend({
YourPluginName: function(options) {
var defaults = {
howMuch:'600',
animation: '',//users can set/change these values
speed: 444,
etc: ''
}
};
options = $.extend(defaults, options);
return this.each(function() {
var $this = $(this);
var button = $('a', $this);// this represents all the 'a' selectors;
// inside user's plugin definition.
button.click(function() {
$this.animate({'top':options.howMuch});//calls options howMuch value
});
});
})(jQuery);
用户凭证:
$(function() {
$('#plugin').YourPluginName({
howMuch:'1000' //you can give chance users to set their options for plugins
});
});
<div id="plugin">
<a>1</a>
<a>2</a>
<a>3</a>
</div>
这篇关于如何创建简单的jQuery插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文