【发布时间】:2011-08-24 04:14:40
【问题描述】:
所以我正在尝试编写我的第一个插件,它在初始化后接受方法和选项。 我正在阅读 JQuery 网站上的 Authoring Plugin 教程,我想出了这个
(function($) {
/* Default Options */
var defaults = {
column_sort_map: []
};
/* Global Scope */
var sort_col = false;
var sortMethods = {
date: function(a, b) {
var date1 = new Date($(a).find(":nth-child(" + sort_col + ")").html());
var date2 = new Date($(b).find(":nth-child(" + sort_col + ")").html());
if (date1 == date2) {
return 0;
}
if (date1 < date2) {
return -1;
}
return 1;
},
string_case: function(a, b) {
var aa = $(a).find(":nth-child(" + sort_col + ")").html();
var bb = $(b).find(":nth-child(" + sort_col + ")").html();
if (aa == bb) {
return 0;
}
if (aa > bb) {
return 1;
}
return -1;
},
string_nocase: function(a, b) {
var aa = $(a).find(":nth-child(" + sort_col + ")").html().toLowerCase();
var bb = $(b).find(":nth-child(" + sort_col + ")").html().toLowerCase();
if (aa == bb) {
return 0;
}
if (aa > bb) {
return 1;
}
return -1;
},
numeric: function(a, b) {
var aa = $(a).find(":nth-child(" + sort_col + ")").html().replace(/\D/g, '');
var bb = $(b).find(":nth-child(" + sort_col + ")").html().replace(/\D/g, '');
if (isNaN(aa)) {
aa = 0;
}
if (isNaN(bb)) {
bb = 0;
}
return aa - bb;
}
};
var methods = {
init: function(options) {
// extend options
if (options) {
$.extend(defaults, options);
}
alert(options.column_sort_map);
},
test: function() {
alert("I am a Test");
}
};
$.fn.dataTable = function(method) {
return this.each(function() {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.dataTable');
}
});
};
})(jQuery);
我用
来称呼它$("#tbl").dataTable({
column_sort_map: [
"numeric",
"string_nocase",
"string_nocase",
"date",
"string_nocase",
"string_nocase",
"numeric"
]
});
$("#tbl").dataTable("test");
HTML 代码非常大,我不想写一个新表。但是对于我的问题,这不是必需的。
我必须再次强调,这是我第一次编写这样的插件。我可能完全误解了本教程,并且出现了严重错误。
我的问题是,当我尝试访问 options.column_sort_map 时出现“未定义”错误。然而,对test 的函数调用按预期工作。
【问题讨论】:
标签: jquery jquery-plugins