html 获取本行td的值,如何通过JavaScript获取html table td cell值?

不要使用内联JavaScript,将您的行为与数据分开,并且它更容易处理。我建议如下:

var table = document.getElementById('tableID'),

cells = table.getElementsByTagName('td');

for (var i=0,len=cells.length; i

cells[i].onclick = function(){

console.log(this.innerHTML);

/* if you know it's going to be numeric:

console.log(parseInt(this.innerHTML),10);

*/

}

}var table = document.getElementById('tableID'),

cells = table.getElementsByTagName('td');

for (var i = 0, len = cells.length; i < len; i++) {

cells[i].onclick = function() {

console.log(this.innerHTML);

};

}

th,

td {

border: 1px solid #000;

padding: 0.2em 0.3em 0.1em 0.3em;

}

Column heading 1Column heading 2Column heading 3Column heading 4

432389543098103272JS Fiddle proof-of-concept。

修改后的方法,以回应评论(below):

You're missing a semicolon. Also, don't make functions within a loop.

此修订将(单个)命名函数绑定为多个

元素的click事件处理程序,并避免在循环内创建多个匿名函数的不必要开销(由于重复和对性能的影响,这是不好的做法,由于内存使用情况):

function logText() {

// 'this' is automatically passed to the named

// function via the use of addEventListener()

// (later):

console.log(this.textContent);

}

// using a CSS Selector, with document.querySelectorAll()

// to get a NodeList of

elements within the #tableID element:

var cells = document.querySelectorAll('#tableID td');

// iterating over the array-like NodeList, using

// Array.prototype.forEach() and Function.prototype.call():

Array.prototype.forEach.call(cells, function(td) {

// the first argument of the anonymous function (here: 'td')

// is the element of the array over which we're iterating.

// adding an event-handler (the function logText) to handle

// the click events on the

elements:

td.addEventListener('click', logText);

});function logText() {

console.log(this.textContent);

}

var cells = document.querySelectorAll('#tableID td');

Array.prototype.forEach.call(cells, function(td) {

td.addEventListener('click', logText);

});

th,

td {

border: 1px solid #000;

padding: 0.2em 0.3em 0.1em 0.3em;

}

Column heading 1Column heading 2Column heading 3Column heading 4

432389543098103272JS Fiddle proof-of-concept。

参考文献:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值