我有一个公共的信息数据库,我想用jQuery,JavaScript(以及后来的HTML和CSS)重新格式化。我正在尝试使用提供的信息在表格中创建新的组。在这个具体的例子中,我想找到8月份的每个实例出现在一个表中。
我尝试了两种方法来搜索内容,并且都返回一个空数组('[]')。这很令人困惑,因为我可以在控制台中记录内容,但它不会添加到新阵列。
//DETECT ROWS, COLUMNS
var tableArray = [];
$("table#tableTest tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
tableArray.push(arrayOfThisRow);
}
});
//SAMPLE LOGS
console.log("R1, C5: " + tableArray[4][3]);
console.log("Total row hits: " + tableArray.length);
//CHECK FOR MONTH (AUGUST)
//Using for
function month() {
//indices represents matches within var text and will be different for each row.
var indices = [];
//This executes for every row, 0 column.
for (var i = 0; i < tableArray.length; i++) {
//text represents the text contents of current position.
var text = tableArray[i][0];
//h represents each letter of text.
for(var h = 0; h < text.length; h++) {
if (text[h] === "A") {
// If we find it, add characters up to
// the length of month to the array
for(var j = h; j < (month.length + h); j++) {
indices.push(text[j]);
};
};
};
//Log every month (works)
//console.log(tableArray[i][0]);
};
return indices;
};
month("August");
//Alternative method
var indices = [];
var element = "August";
var idx = tableArray.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = tableArray.indexOf(element, idx + 1);
}
console.log(indices);
答案 0 :(得分:1)
你没有在任何地方使用month()
函数的参数。
function month(monthname) {
var indices = [];
$.each(tableArray(function(rowNum, row) {
$.each(row, function(colNum, col) {
if (col.indexOf(monthname) != -1) {
indices.push(col);
}
});
});
return indices;
}
答案 1 :(得分:0)
使用jQuery你也可以这样做:
function month (elem, needle) {
elem.find("td:contains('"+needle+"')").each(function() {
console.log(this);
})
}
month($('table'), "AUGUST");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td>AUGUST</td>
</tr>
<tr>
<td>MAY</td>
</tr>
<tr>
<td>APRIL</td>
</tr>
<tr>
<td>JUNE</td>
</tr>
<tr>
<td>AUGUST</td>
</tr>
<tr>
<td>SEPTEMBER</td>
</tr>
<tr>
<td>AUGUST</td>
</tr>
<tr>
<td>JUNE</td>
</tr>
<tr>
<td>AUGUST</td>
</tr>
<tr>
<td>MAY</td>
</tr>
</table>
&#13;