Как получить значение ячейки таблицы с помощью jQuery?
Я пытаюсь выяснить, как получить значение ячейки таблицы для каждой строки с помощью jQuery.
Моя таблица выглядит так:
<table id="mytable">
<tr>
<th>Customer Id</th>
<th>Result</th>
</tr>
<tr>
<td>123</td>
<td></td>
</tr>
<tr>
<td>456</td>
<td></td>
</tr>
<tr>
<td>789</td>
<td></td>
</tr>
</table>
Я в основном хочу прокрутить таблицу и получить значение столбца Customer Id
для каждой строки.
В приведенном ниже коде я разработал, что мне нужно сделать это, чтобы он прошел через каждую строку, но я не уверен, как получить значение первой ячейки в строке.
$('#mytable tr').each(function() {
var cutomerId =
}
Ответы
Ответ 1
Если вы можете, возможно, стоит использовать атрибут класса в TD, содержащий идентификатор клиента, чтобы вы могли написать:
$('#mytable tr').each(function() {
var customerId = $(this).find(".customerIDCell").html();
});
По сути, это то же самое, что и другие решения (возможно, потому что я вставил копию), но имеет то преимущество, что вам не нужно менять структуру кода, если вы перемещаетесь по столбцам или даже помещаете идентификатор клиента в <span>
, если вы сохраняете атрибут класса вместе с ним.
Кстати, я думаю, вы могли бы сделать это в одном селекторе:
$('#mytable .customerIDCell').each(function() {
alert($(this).html());
});
Если это облегчает жизнь.
Ответ 2
$('#mytable tr').each(function() {
var customerId = $(this).find("td:first").html();
});
Что вы делаете, это итерация через все trs в таблице, поиск первого td в текущем tr в цикле и извлечение его внутреннего html.
Чтобы выбрать конкретную ячейку, вы можете ссылаться на нее с индексом:
$('#mytable tr').each(function() {
var customerId = $(this).find("td").eq(2).html();
});
В приведенном выше коде я получаю значение третьей строки (индекс основан на нуле, поэтому первым индексом ячейки будет 0)
Здесь вы можете сделать это без jQuery:
var table = document.getElementById('mytable'),
rows = table.getElementsByTagName('tr'),
i, j, cells, customerId;
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue;
}
customerId = cells[0].innerHTML;
}
Ответ 3
менее прочный подход:
$('#mytable tr').each(function() {
if (!this.rowIndex) return; // skip first row
var customerId = this.cells[0].innerHTML;
});
это, очевидно, может быть изменено для работы с не-первыми ячейками.
Ответ 4
Попробуйте это,
$(document).ready(function(){
$(".items").delegate("tr.classname", "click", function(data){
alert(data.target.innerHTML);//this will show the inner html
alert($(this).find('td:eq(0)').html());//this will alert the value in the 1st column.
});
});
Ответ 5
$('#mytable tr').each(function() {
// need this to skip the first row
if ($(this).find("td:first").length > 0) {
var cutomerId = $(this).find("td:first").html();
}
});
Ответ 6
Вы не используете идентификатор для этого столбца?
скажите, что:
<table width="300" border="1">
<tr>
<td>first</td>
</tr>
<tr>
<td>second</td>
</tr>
<tr>
<td>blah blah</td>
<td>blah blah</td>
<td id="result">Where the result should occur</td>
</tr>
</table>
<script type="text/javascript">
$('#result').html("The result is....");
</script>
Ответ 7
Это работает
$(document).ready(function() {
for (var row = 0; row < 3; row++) {
for (var col = 0; col < 3; col++) {
$("#tbl").children().children()[row].children[col].innerHTML = "H!";
}
}
});
Ответ 8
попробуйте следующее:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript"><!--
function getVal(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
alert(targ.innerHTML);
}
onload = function() {
var t = document.getElementById("main").getElementsByTagName("td");
for ( var i = 0; i < t.length; i++ )
t[i].onclick = getVal;
}
</script>
<body>
<table id="main"><tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr><tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr><tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr></table>
</body>
</html>
Ответ 9
$(document).ready(function() {
var customerId
$("#mytable td").click(function() {
alert($(this).html());
});
});
Ответ 10
Рабочий пример:
http://jsfiddle.net/0sgLbynd/
<table>
<tr>
<td>0</td>
<td class="ms-vb2">1</td>
<td class="ms-vb2">2</td>
<td class="ms-vb2">3</td>
<td class="ms-vb2">4</td>
<td class="ms-vb2">5</td>
<td class="ms-vb2">6</td>
</tr>
</table>
$(document).ready(function () {
//alert("sss");
$("td").each(function () {
//alert($(this).html());
$(this).html("aaaaaaa");
});
});