![](/img/trans.png)
[英]how to get a particular cell value from dynamic table using javascript
[英]How do I get the cell value from a table using JavaScript?
<td> <input type="button" name="buton" id="x2" value="2" onclick="swap(id)";/> </td>
單擊時,這是表中的按鈕,其ID作為參數傳遞給函數“交換”,如下所示:
function swap(x)
{
document.write(x);
}
當我以這種方式嘗試時,成功獲取id而不是值;
function swap(x)
{
document.write(x.value);
}
輸出顯示為未定義。 您能告訴我如何使用單元格ID來獲取單元格值嗎?
我相信您正在尋找的是document.getElementById(x).value; 另外,如果您希望按鈕將其傳遞給如下函數:
<button onclick="foo(this)"/>
我猜想使用jQuery為目的,它允許非常輕松地遍歷DOM。
<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>
如果可以的話,可能值得在TD上使用包含客戶ID的class屬性,這樣您就可以編寫:
$('#mytable tr').each(function() {
var customerId = $(this).find(".customerIDCell").html();
}
從本質上講,這與其他解決方案相同(可能是由於我復制粘貼了),但具有的優點是,如果您在各列之間移動,甚至無需將客戶ID放入<span,就無需更改代碼的結構。 >,前提是您保留了class屬性。
順便說一句,我認為您可以在一個選擇器中完成此操作:
$('#mytable .customerIDCell').each(function()
{
alert($(this).html());
});
如果那使事情變得容易
在交叉Bowser問題上,代碼將或多或少更可靠
如果要傳遞元素的ID,則可能要使用document.getElementById(x)
來訪問它。
z = document.getElementById(id);
首先,然后您應該可以使用z.firstChild.textContent
您需要使用var cell = document.getElementById(x)
來獲取單元var cell = document.getElementById(x)
。 然后使用cell.firstChild.nodeValue
。
function swap(x)
{
var cell = document.getElementById(x);
document.write(cell.firstChild.nodeValue);
}
編輯:在FF3.5和IE8上都對此進行了測試,並且可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.