【发布时间】:2015-03-02 17:17:43
【问题描述】:
我正在使用table2excel 插件,它允许我将表格内容下载到 Excel 文件中。它第一次运行良好,但每次页面加载只能让我下载一次。
我尝试将$("#export").click(function(){ 更改为$("#export").on('click', function(){,但这不起作用。 $('#export').click 已在文档中准备就绪
// click function on page
$("#export").click(function(){
$("#table2excel").table2excel({
// exclude CSS class
exclude: ".noExl",
name: "Excel Document Name"
});
});
// external js file that gets called
//table2excel.js
;(function ( $, window, document, undefined ) {
var pluginName = "table2excel",
defaults = {
exclude: ".noExl",
name: "Table2Excel"
};
// The actual plugin constructor
function Plugin ( element, options ) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don't want to alter the default options for
// future instances of the plugin
this.settings = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
var e = this;
e.template = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><!--[if gte mso 9]><xml>";
e.template += "<x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions>";
e.template += "<x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>";
e.tableRows = "";
// get contents of table except for exclude
$(e.element).find("tr").not(this.settings.exclude).each(function (i,o) {
e.tableRows += "<tr>" + $(o).html() + "</tr>";
});
this.tableToExcel(this.tableRows, this.settings.name);
},
tableToExcel: function (table, name) {
var e = this;
e.uri = "data:application/vnd.ms-excel;base64,";
e.base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)));
};
e.format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
e.ctx = {
worksheet: name || "Worksheet",
table: table
};
window.location.href = e.uri + e.base64(e.format(e.template, e.ctx));
}
};
$.fn[ pluginName ] = function ( options ) {
this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
// chain jQuery functions
return this;
};
})( jQuery, window, document );
【问题讨论】:
-
后续点击是否会触发点击回调(初始点击后)?你能分享一个可以重现的沙箱吗?
-
检查控制台错误;如果您的浏览器在运行函数时捕获到一个,它将阻止任何后续调用运行。在 Firefox 或 Chrome 中,按
F12打开开发者工具,按export时检查console标签。 -
我从未使用过该插件,但听起来确实很有趣,但我只是想知道您是否也为第二次单击使用相同的文件名。如果是这样,您可以尝试使用不同的名称,例如在名称中添加一些索引值。每次点击 index + 1 或类似的东西后,可以更改索引值。
-
哇,谢谢你的小提琴。现在我对其进行了测试——我第一个通过 Web 浏览器创建的 excel 文件 :-)
标签: javascript jquery