如何通过单击按钮获取单元格值
我有一个问题,我解决不了多少问题。通过点击编辑客户按钮我不想从CustomerNr单元中获取值。我的问题是,我不知道如何通过单击按钮来获取行索引,然后将其传递给我的函数,以便我可以明确地获取该行上的CustomerNr,我按下了该按钮。你可以看看我的jsfiddle链接,并注意,这是我第一次使用Javascript/Jquery编码。我愿意提供智能解决方案。如何通过单击按钮获取单元格值
在这里你可以看到我有多远。我设法从特定的单元格中选择值。
function GetCellValues() {
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
}
我设法通过点击一个TD获得行索引,但我想通过按下一个按钮来得到它。
function myMethod(obj) {
alert(obj.parentNode.rowIndex); // parentNode is also used
}
我不想以某种方式结合这两个函数,就像在C#中。 (我是一个C#程序员)
function GetCellValues(e) {
//Something here
alert(Cells[0].Rows[e] innerText);
}
我已经改变了的ID是你的按钮上课,因为你不能命名具有相同ID的两个元素,然后我通过元素循环... Working fiddle
您应该避免使用内联函数和perefer巧妙地像这样做,这可能安全,你大量的时间,并保持它更好的可维护性:
的Javascript:
var a = document.getElementsByClassName('otherButton');
for (var i = 0; i<a.length;i++) {
a[i].addEventListener('click',function(){
var b = this.parentNode.parentNode.cells[0].textContent;
alert(b);
});
}
HTML:
<table id="somerow">
<tr>
<th>CustomerNr</th>
<th>Name</th>
<th>Contact</th>
</tr>
<tr >
<td>1</td>
<td>Cigarettes Inc</td>
<td>Rambo</td>
<td>
<button class="otherButton" >Edit Customer</button>
</td>
</tr>
<tr >
<td >22</td>
<td>Razor</td>
<td>David</td>
<td>
<button class="otherButton">Edit Customer</button>
</td>
</tr>
<tr>
<td>3</td>
<td>H&M</td>
<td>Samuel Adams</td>
<td>
<button class="otherButton" >Edit Customer</button>
</td>
</tr>
}
按钮是作为TR里面,所以你需要去2个节点组成的TD内。试试这个:
这是行不通的,如果不修改代码最好想要传递一个元素,现在,obj将是未定义的。看到我的小提琴正确工作的例子 – dandavis 2014-12-07 00:01:31
HTML
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
.selected {
background-color: yellow;
}
</style>
</head>
<body>
<center>
<table id="somerow">
<tr>
<th>CustomerNr</th>
<th>Name</th>
<th>Contact</th>
</tr>
<tr>
<td>1</td>
<td>Cigarettes Inc</td>
<td>Rambo</td>
<td>
<button id="otherButton" onclick="GetCellValues()">Edit Customer</button>
</td>
</tr>
<tr>
<td onclick="myMethod(this);">22</td>
<td>Razor</td>
<td>David</td>
<td>
<button id="otherButton" onclick="GetCellValues()">Edit Customer</button>
</td>
</tr>
<tr>
<td>3</td>
<td>H&M</td>
<td>Samuel Adams</td>
<td>
<button id="otherButton" onclick="GetCellValues()">Edit Customer</button>
</td>
</tr>
</center>
</body>
</html>
JS
function GetCellValues(elm) {
alert(elm.parentNode.parentNode.cells[0].textContent);
}
function myMethod(obj) {
alert(obj.parentNode.rowIndex);
}
可以触发传递给处理程序,然后使用parentNode达到td和tr:http://jsfiddle.net/6srjc7qL/3/ – dandavis 2014-12-06 23:53:58
@dandavis是的按钮位于之间的单元格 – 2014-12-06 23:55:08