Javascript 需要帮助理解这个简单的jQuery代码吗
此代码将HTML表转换为CSV文件。我不明白这两行:Javascript 需要帮助理解这个简单的jQuery代码吗,javascript,jquery,Javascript,Jquery,此代码将HTML表转换为CSV文件。我不明白这两行: $(document).ready(function () { function exportTableToCSV($table, filename) { var $rows = $table.find('tr:has(td)'), // Temporary delimiter characters unlikely to be typed by keyboard // This is to av
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// This must be a hyperlink
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
及
什么是“i”和“j”?它们不在函数中的任何地方使用,也没有循环,所以在哪里使用这些变量。它们是否在“映射”功能中使用
这些行是函数声明。这些函数是匿名的i
和j
是传递给函数的参数的名称。它们可能不被使用,但仍然需要作为传递给它们的第一个参数的名称存在
有关如何调用回调的说明,请参阅的文档。jquery map函数需要一个包含两个参数的回调,即元素的索引和元素。 因此$rows.map(函数(i,row){…});将在第一个参数中接收行(0,1…)的索引,在第二个参数中接收行本身的索引 如果从函数调用中删除i,则只映射第一个值,因此,行(而不是接收行的值)将接收索引(0,1…) 顺便说一句,映射是(行,索引),所以映射错误(在回调定义中) 如果它们有独立的功能,它会是这样的
function (i, row) {
function (j, col) {
void映射($rows)
{
$arr=[];
对于($i=0;$istill不理解。我从函数中删除了它们,但下载的cvs文件为空。添加行console.log(i,行);
作为函数的第一行。然后在控制台中观察这两个参数的值。从函数声明和log语句中删除第一个参数,并查看其差异。但是“i”和“j”在哪里递增?它不是。它是传递给函数的参数。您熟悉f是如何递增的吗调用函数并传递参数?这可能会有帮助:但“i”和“j”在哪里递增?i、j和row由map函数递增并管理,map将调用该函数的次数与$rows variable中包含的行的次数相同抱歉,但是您是否能够以函数彼此之外的方式重新编写该函数,i无法理解发生了什么。例如,正如您所说的“map”函数接受2个参数,但在本例中,另一个函数的返回值仅为1个参数,并传递给它上面的map函数
function (j, col) {
function (i, row) {
function (j, col) {
void map($rows)
{
$arr = [];
for($i=0; $i<$rows.length; $i++)
{
$arr.push(mapping_function($i,$rows[i]));
}
return $arr;
}
void mapping_function($i, $row)
{
...
}