我有一個10 X 8表。獲取特定表「td」元素的信息
每一行都有8列即8個td元素。行中的每個td都有不同的類。是否有可能獲得行中第一個td元素的信息,當我點擊行中的任何其他td時。
基本上我在每列的第2列到第8列創建一個jQuery onclick事件。當我點擊任何一列(td)時,它應該得到信息ie ..,無論是ID或類或名稱屬性的第1列。我需要這一個發送它在服務器端代碼。
- 謝謝。
我有一個10 X 8表。獲取特定表「td」元素的信息
每一行都有8列即8個td元素。行中的每個td都有不同的類。是否有可能獲得行中第一個td元素的信息,當我點擊行中的任何其他td時。
基本上我在每列的第2列到第8列創建一個jQuery onclick事件。當我點擊任何一列(td)時,它應該得到信息ie ..,無論是ID或類或名稱屬性的第1列。我需要這一個發送它在服務器端代碼。
- 謝謝。
是的。從點擊的元素,您通過closest
向上導航到該行,那麼你就可以找到td
與相關類find
或children
(可能children
如果你有嵌套表):
function clickHandler(e) {
var cell = $(e.target).closest('tr').children('td.foo');
// ...
}
或者,如果你總是希望第一td
:
var cell = $(e.target).closest('tr').children('td').first();
也就是說,如果它分配給任何td
在處理程序將工作該表,到tr
,或者實際到tbody
或table
作爲一個整體。
的JavaScript:
jQuery(function($) {
// Put the handler on the tbody
$("#target").click(clickHandler);
function clickHandler(e) {
var td = $(e.target).closest('tr').children('td').first();
display("The text of the first <code>td</code> in that row is: " + td.text());
}
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
});
HTML:
<table>
<tbody id="target">
<tr>
<td class="one">This is one in row 0</td>
<td class="two">This is two in row 0</td>
<td class="three">This is three in row 0</td>
</tr>
<tr>
<td class="one">This is one in row 1</td>
<td class="two">This is two in row 1</td>
<td class="three">This is three in row 1</td>
</tr>
<tr>
<td class="one">This is one in row 2</td>
<td class="two">This is two in row 2</td>
<td class="three">This is three in row 2</td>
</tr>
</tbody>
</table>
基本上你可以像:
$('td.column2-8').click(function()
{
var firstTdData = $(this).parent().children('td:first').html();
});
$('td').click(function(){
var $elem = $(this).parent('tr').children('td:first');
var elem_id = $elem.prop('id'); // or $elem.attr('id');
.... // for class, name, etc.
});
感謝您的詳細信息,其工作。 Btw一個小的查詢,是在點擊事件,我可以追加一個隱藏的輸入與名稱=「名稱的第一個TD:和價值=」值的第一個TD「我試圖使用 - $(」#電視節目-feeds-form「)。append('') ;但它不起作用。 –
@SangramAnand:['td' elements](http://www.w3.org/TR/html5/the-td-element.html#the-td-element)沒有'name'屬性或者一個'value',這就是爲什麼不起作用(cell.attr(「name」)'和'cell.val()'可能會返回'「」')。您可以按照您的指示添加字段,但我不知道您想要的名稱和值的單元格的哪一部分。 (也許你認爲「價值」是指單元格的文本?那將是'cell.text()',但我不知道你的名字是什麼意思)。無論如何,這將是一個不同的問題。 *我相信這個問題已經回答了。 :-) –
是的,它的工作。謝謝你.. :-) –