我的问题是我无法使用我创建的功能。你可以看到下面的代码。我得到的是“非功能错误”。
var alteropacity = function () { //creating function
if ($(this).css('opacity') < '0.90') {
$(this).css('opacity', '1.00');
}
else {
$(this).css('opacity', '0.20');
}
return $(this);
};
$("#image").on("click", function () { //using it
$(this).alteropacity();
});
答案 0 :(得分:6)
要使函数作为jQuery方法可用,您必须向$.fn
添加属性:
$.fn.alteropacity = alteropacity;
在函数声明之后(在事件处理程序之外)添加它。
现在,虽然您的代码可以正常运行,但如果真的想要创建一个jQuery方法,它应该遵循约定(如果这对函数的目的有意义)。在这种情况下,它只是意味着迭代:
var alteropacity = function () {
return this.each(function() {
if ($(this).css('opacity') < '0.90') {
$(this).css('opacity', '1.00');
}
else {
$(this).css('opacity', '0.20');
}
});
};
这样,如果您要执行类似
的操作,该方法将起作用$(".common-class").alteropacity();
也就是说,如果您要使用该函数来影响许多元素。另请注意,在jQuery方法中,this
引用了要为其调用方法的jQuery对象。将它再次包裹起来并没有什么坏处($(this)
),但你不必这样做。但是,在.each()
迭代内部,您回到熟悉的区域,因此回调中的this
将引用所涉及的元素。