不要使用内联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。参考文献: