这是我的代码:
(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();
});
Run Code Online (Sandbox Code Playgroud)
它给了我一个错误.怎么了?
Pri*_*ERO 90
通过使用匿名函数传递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>
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
Gab*_*oli 10
更改
});
$(document).ready(function () {
$('.smallTabsHeader a').pluginbutton();
});
Run Code Online (Sandbox Code Playgroud)
至
})(jQuery); //<-- ADD THIS
$(document).ready(function () {
$('.smallTabsHeader a').pluginbutton();
});
Run Code Online (Sandbox Code Playgroud)
这是必需的,因为您需要调用您创建的匿名函数
(function($){
Run Code Online (Sandbox Code Playgroud)
并注意到它需要一个将在内部使用的参数$,因此您需要传递对jQuery对象的引用.
此外,您将需要改变所有的this.到$(this).,除了第一个,在你做return this.each
在第一个(你不需要的地方$())这是因为在插件体中,this持有对与你的选择器匹配的jQuery对象的引用,但是在比这更深的地方this引用特定的DOM元素,所以你需要包装它在$().
http://jsfiddle.net/gaby/NXESk/上的完整代码
当另一个系统抓取$变量时会出现问题.您有多个$变量用作多个库中的对象,从而导致错误.
要解决它,请在您之前使用jQuery.noConflict(function($){:
jQuery.noConflict();
(function($){
$.fn.pluginbutton = function (options) {
...
Run Code Online (Sandbox Code Playgroud)