获取HTML表中单击的列中第一个单元格和单击的行中第一个单元的内容
Get contents of the first cell in the clicked column and the first cell of the clicked row in a HTML table
我正在使用以下javascript获取点击的表格单元格中的数据:
var table = document.getElementById('ThisWeek'),
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++)
{
cells[i].onclick = function()
{
document.getElementById("txtVal").value = this.innerText;
}
}
我如何修改它,以便也可以获得单击的列中第一个单元格和单击的行中第一个单元的内容?例如,如果我点击下表中的"s",我会得到作为两个变量返回的结果"2"answers"B":
0 1 2 3
A q w e
B a s d
C z x c
请注意,我需要一个javascript解决方案,而不是jQuery。理想情况下,我还希望单击第一行和第一列以返回空字符串。
这个片段使用了我在评论中提到的属性:
window.onload = function () {
var table = document.getElementById('table');
table.addEventListener('click', function (e) {
var target = e.target,
col = target.cellIndex,
row;
while (target = target.parentElement) {
if (!col && col !== 0) {
col = target.cellIndex;
}
if (target.tagName.toLowerCase() === 'tr') {
row = target.rowIndex;
break;
}
}
console.log(table.rows[row].cells[0].innerHTML + ', ' + table.rows[0].cells[col].innerHTML);
});
}
jsFiddle的现场演示。
我建议:
function index(c){
var i = 0;
while (c.previousSibling){
/* if the previousSibling has a nodeType and that nodeType === 1
(indicating the previousSibling is an element) increment the i variable */
if (c.previousSibling.nodeType && c.previousSibling.nodeType === 1){
i++;
}
// reset c to the previousSibling
c = c.previousSibling;
}
/* i is the count of previous-siblings, and therefore the index
amongst those siblings: */
return i;
}
function getHeaders(e){
/* this is the table element,
e.target is the clicked element */
var el = e.target,
text = 'textContent' in document ? 'textContent' : 'innerText',
headers = [el.parentNode.getElementsByTagName('td')[0][text],this.getElementsByTagName('tr')[0].getElementsByTagName('td')[index(el)][text]];
// set the text of the nextElementSibling of the table:
this.nextElementSibling[text] = headers.join(', ');
}
document.getElementById('table').addEventListener('click', getHeaders);
JS Fiddle演示。
您可以将其添加到您的单元格[i].onclick函数:
var row = this.parentElement; // TR
var table = row.parentElement.parentElement; // TBODY > TABLE
document.getElementById("columnVal").value = row.rowIndex && this.cellIndex ? table.rows[0].cells[this.cellIndex].innerText : "";
document.getElementById("rowVal").value = row.rowIndex && this.cellIndex ? row.cells[0].innerText : "";
相关文章:
- 删除确认对话框在第一次单击时不起作用
- Spring WebFlow2 Javascript只在第一个单选按钮上工作
- 在Rails中第一次单击后禁用链接,Coffeescription
- 在没有焦点的情况下捕获画布上的第一次单击事件
- Javascript onclick事件在第一次单击时未启动
- 在单击事件中,第一次单击时激发代码一次,其余代码在所有单击时运行
- 无法在第一次单击时禁用链接,并在动画完成后重新启用
- 无法在第一次单击事件时提交表单
- Ajax第一次单击
- 操作方法:第一次单击动画 1,第二次单击动画 2
- 如何在第一次单击后禁用搜索按钮,直到结果来自服务器
- 传单切换按钮仅在第一次单击时起作用
- 停止滚动到每个点击的链接,只滚动到第一个点击的链接
- JQuery切换功能仅在第一次单击时起作用
- 在javascript中第一次单击行时获取表单元格值
- 回发后第一次单击按钮时,OnClientClick未触发
- 设置第一个单选按钮是在车把模板中检查的
- 使页面滚动只有第一个单选按钮点击
- 多个设置超时函数在第一次单击时不执行
- 仅在第一次单击时从多个文本区域删除文本