这个测试插件应该像这样工作:单击一个元素时,它会向下移动。就那么简单。
jQuery.fn.moveDown = function(howMuch){
$(this).css("border", "1px solid black");
$(this).click(function(){
$(this).css("position", "relative");
$(this).animate({top: '+='+howMuch});
});
}
问题是,当点击一个元素时,它不仅会移动被点击的元素,还会移动插件所应用的所有其他元素。
这是什么解决方案?
答案 0 :(得分:5)
对于插件创作尝试这种方式,更加可靠:
编辑: Here is working jsFiddle example.
插件:
(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>
答案 1 :(得分:0)
在这里,我想建议使用参数创建简单插件的步骤。
<强> JS 强>
(function($) {
$.fn.myFirstPlugin = function( options ) {
// Default params
var params = $.extend({
text : 'Default Title',
fontsize : 10,
}, options);
return $(this).text(params.text);
}
}(jQuery));
在这里,我们添加了名为params
的默认对象,并使用extend
函数设置选项的默认值。因此,如果我们传递空白参数,那么它将设置默认值,否则它将设置。
<强> HTML 强>
$('.cls-title').myFirstPlugin({ text : 'Argument Title' });
了解详情: How to Create JQuery plugin
原始回答 Here i want to suggest steps to create simple plugin with arguments
答案 2 :(得分:0)
如果已安装Node.js,则可以使用create-jquery-plugin CLI实用程序。刚运行
npx create-jquery-plugin
或者,您可以克隆jquery-plugin-boilerplate 开始。