这里是我的代码:
(function($){ $.fn.pluginbutton = function (options) { myoptions = $.extend({ left: true }); return this.each(function () { var focus = false; if (focus === false) { this.hover(function () { this.animate({ backgroundPosition: "0 -30px" },{ duration: 0 }); this.removeClass('VBfocus').addClass('VBHover'); },function () { this.animate({ backgroundPosition: "0 0" },{ duration: 0 }); this.removeClass('VBfocus').removeClass('VBHover'); }); } this.mousedown(function () { focus = true this.animate({ backgroundPosition: "0 30px" },{ duration: 0 }); this.addClass('VBfocus').removeClass('VBHover'); },function () { focus = false; this.animate({ backgroundPosition: "0 0" },{ duration: 0 }); this.removeClass('VBfocus').addClass('VBHover'); }); }); } }); $(document).ready(function () { $('.smallTabsHeader a').pluginbutton(); });
它给我一个错误。怎么了?
解决方法
这个问题是“最好的”解决通过使用
anonymous function传入jQuery对象因此:
匿名函数看起来像:
<script type="text/javascript"> (function($) { // You pass-in jQuery and then alias it with the $-sign // So your internal code doesn't change })(jQuery); </script>
这是JavaScript的实现“依赖注入”的方法,当与“模块模式”一起使用时。
所以你的代码看起来像:
当然,你可能想现在对你的内部代码做一些修改,但你得到的想法。
<script type="text/javascript"> (function($) { $.fn.pluginbutton = function(options) { myoptions = $.extend({ left: true }); return this.each(function() { var focus = false; if (focus === false) { this.hover(function() { this.animate({ backgroundPosition: "0 -30px" },{ duration: 0 }); this.removeClass('VBfocus').addClass('VBHover'); },function() { this.animate({ backgroundPosition: "0 0" },{ duration: 0 }); this.removeClass('VBfocus').removeClass('VBHover'); }); } this.mousedown(function() { focus = true this.animate({ backgroundPosition: "0 30px" },{ duration: 0 }); this.addClass('VBfocus').removeClass('VBHover'); },function() { focus = false; this.animate({ backgroundPosition: "0 0" },{ duration: 0 }); this.removeClass('VBfocus').addClass('VBHover'); }); }); } })(jQuery); </script>