在jQuery中,我已经看到了以下两种定义jQuery函数的方法:
$.fn.CustomAlert = function() {
  alert('boo!');
};
$.CustomAlert = function() {
  alert('boo!');
};
我知道它们附加到jQuery对象(或$),但两者之间有什么区别?我什么时候应该使用其中一种?
谢谢.
Anu*_*rag 66
我确定之前曾多次询问过这个问题,但我找不到链接.
$.fn指向jQuery.prototype.您添加到它的任何方法或属性都可用于jQuery包装对象的所有实例.
$.something 向jQuery对象本身添加属性或函数.
$.fn.something当您在页面上处理DOM元素时使用第一个表单,并且您的插件对元素执行某些操作.当插件与DOM元素无关时,请使用其他形式$.something.
例如,如果你有一个记录器功能,那么将它与DOM元素一起使用没有多大意义,如:
$("p > span").log();
对于这种情况,您只需将日志方法添加到jQuery对象iself:
jQuery.log = function(message) {
    // log somewhere
};
$.log("much better");
但是,在处理元素时,您可能希望使用其他形式.例如,如果您有一个从a获取数据<table>并生成图形的图形插件(plotGraph)- 您将使用该$.fn.*表单.
$.fn.plotGraph = function() {
    // read the table data and generate a graph
};
$("#someTable").plotGraph();
在相关的说明中,假设您有一个可以与元素或独立一起使用的插件,并且您希望将其作为$.myPlugin或访问它$("<selector>").myPlugin(),您可以为两者重用相同的功能.
假设我们想要一个自定义警报,其中日期前置于每个警报消息.当用作独立函数时,我们将消息作为参数传递给它,当与元素一起使用时,它使用text元素作为消息:
(function($) {
    function myAlert(message) {
        alert(new Date().toUTCString() + " - " + message);
    }
    $.myAlert = myAlert;
    $.fn.myAlert = function() {
        return this.each(function() {
            myAlert($(this).text());
        });
    };
})(jQuery);
它包含在一个自动执行的函数中,因此myAlert不会溢出到全局范围.这是两个插件表单之间的示例或重用功能.
正如theIV所提到的,返回jQuery包装元素本身是一个好习惯,因为你不想破坏链接.
最后,我发现了类似的问题:-)
svi*_*nto 12
一个
$.a = function() {
  return "hello world";
};
alert($.a());
乙
$.fn.b = function() {
  return "hello " + $(this).length + " elements";
}
alert($("p").b());
| 归档时间: | 
 | 
| 查看次数: | 12010 次 | 
| 最近记录: |