我需要编写一个脚本来从表中获取数据并提醒他们,但我不知道该怎么做。现在我只知道如何获取按钮名称并提醒它。我如何从表中获取数据并使用jQuery提醒它?
数据:
<button id = 'btnMain'> Click me </button>
<table id = 'resultsTable' border = '1'>
<tr>
<td> one </td>
<td> two </td>
<td> three </td>
</tr>
<tr>
<td> four </td>
<td> five </td>
<td> six </td>
</tr>
</table>
脚本:
(function() {
'use strict';
$("#btnMain").click(function(){
var text = document.getElementById("btnMain").innerHTML;
alert(text);
});
})(); //end of (function()
结果:提醒“点击我”。
需要结果:提醒“一二三四五六”。
我需要将TD的结果分开,因为我需要将它们分配给不同的变量。例如,tr1td1 = 1,tr1td2 = 2,等等......稍后我将需要使用这些变量。
答案 0 :(得分:1)
您可以循环遍历以下元素:
$("#btnMain").click(function() {
$('#resultsTable td').each(function(){
console.log(this.innerHTML)
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btnMain'> Click me </button>
<table id='resultsTable' border='1'>
<tr>
<td> one </td>
<td> two </td>
<td> three </td>
</tr>
<tr>
<td> four </td>
<td> five </td>
<td> six </td>
</tr>
</table>
&#13;
答案 1 :(得分:0)
表中所有tds的简单迭代就可以了。使用行和单元格的索引,我们可以将变量存储在2D数组中。
function getData() {
var totalRows = $('#resultsTable tr').length;
//Initialize your 2D array
var cellData = [];
//This step is necessary otherwise cellData[3][1] assign will fail due to undefined error
//Arbitary 2D array initialization is not possible for this case
for (var i = 0; i < totalRows; i++) {
cellData[i] = [];
}
var cellText = '';
$('#resultsTable td').each(function() {
cellText += $(this).html();
var rowNum = $(this).parent().index();
var cellNum = $(this).index();
//Save data for later use
cellData[rowNum][cellNum] = $(this).html();
});
alert(cellText);
console.log(cellData);
}
$("#btnMain").click(function() {
getData();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btnMain'> Click me </button>
<table id='resultsTable' border='1'>
<tr>
<td> one </td>
<td> two </td>
<td> three </td>
</tr>
<tr>
<td> four </td>
<td> five </td>
<td> six </td>
</tr>
</table>
&#13;
答案 2 :(得分:0)
试试这种方式。
(function() {
'use strict';
$("#btnMain").click(function(){
var tds = $("#resultsTable td"); // select all tds instead selecting button
var tableValues = "";
for(var i=0;i<tds.length; i++) {
var value = tds.eq(i).text(); // manipulate each value here
tableValues += " " + value;
tableValues = tableValues.trim();
}
alert(tableValues); // all values separated by space
});
})(); //end of (function()
要单独获得结果,只需执行
var arrValues = tableValues.split(" "); // it will return a array with all your values
答案 3 :(得分:0)
这应该这样做:
var text = document.getElementById("resultsTable");
var arr_of_tr_elements = text.children[0].children;
all = '';
for (var tr of arr_of_tr_elements) {
for (var td of tr.children) {
all += td.textcontent;
}
}
alert (all);