由于范围,您正在遇到问题。该函数不可用,因为它在每个语句中。
但是,你可以像this这样的东西,并作出选项列表,然后传递你想使用的选项。同样,你可以做到这一点,所以你可以通过自定义函数。
<p id="red">Red colored</p>
<p id="green">Green colored</p>
<p id="blue">Blue colored</p>
<div>This is a custom function</div>
(function($){
$.fn.extend({
color: function(method){
// list of possible methods
var methods = {
red: function(a){ return '<span style="color:red;">'+a+'</span>' },
green: function(a){ return '<span style="color:green;">'+a+'</span>' },
blue: function(a){ return '<span style="color:blue;">'+a+'</span>' },
}
// assign the appropriate function based on the "method" argument
var func = methods[method] || function(a){ return a; };
// run through the elements and apply that function
return this.each(function(i,e){
$(e).html(func($(e).html()));
});
},
color2: function(func){
func = func || function(a){ return a; };
return this.each(function(i,e){
$(e).html(func($(e).html()));
});
}
});
})(jQuery);
$('p').each(function(i,e){
$(e).color($(e).attr('id'));
});
$('div').color2(function(a){
return '<b style="color:#FF00FF">'+a+'</b>';
});
的color
可以传递在方法对象中找到的名称。 color2
可以传递一个完整的函数,所以你可以扩展你想要做的事情。 (你可以检查参数并根据参数的类型改变行为,但这是为了演示)。