基本功能如何能够附加到(并操纵)所选元素?
E.g。显示一个隐藏的元素:
mySelectedElement.hideElement();
使用以下代码尝试上述操作会出现此错误:
TypeError:$(...)。hideElement不是函数
function hideElement() {
this.css({
display: none
});
return this;
答案 0 :(得分:6)
试试这个:你需要用jquery方式定义函数,见下面的函数
如果在js文件中定义函数 -
$.fn.hideElement= function() {
$(this).css({
display: 'none'
});
};
如果在$(document).ready(..
-
var hideElement = function() {
$(this).css({
display: 'none'
});
};
答案 1 :(得分:3)
创建jQuery插件的语法
(function($){
$.fn.<yourfn> = function(opt){
//Take care of jQuery chaining by return this
//Take care of multiple selections say $('div, span, p').<yourfn>() using .each
return this.each(
function(){
/* your TODO goes here */
};
);
};
})(jQuery);
所以你的hideElement函数应该像
(function($){
$.fn.showElement = function(options){
return this.each(
function(){
$(this).css({display: none});
};
);
};
})(jQuery);
致电$('div,p').hideElement();