本文介绍了如何创建简单的 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 示例.
插件:
(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 插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!