本文介紹了如何創(chuàng)建簡單的 jQuery 插件?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
這個測試插件應(yīng)該是這樣工作的:當(dāng)一個元素被點擊時,它會向下移動.就那么簡單.
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});
});
}
問題是,當(dāng)一個元素被點擊時,它不僅會移動被點擊的元素,還會移動應(yīng)用插件的所有其他元素.
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.
解決辦法是什么?
推薦答案
對于插件創(chuàng)作嘗試這種方式,更可靠:
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>
這篇關(guān)于如何創(chuàng)建簡單的 jQuery 插件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!