html5 table onclick,JavaScript table onclick

I'll update with a method to toggle the highlight to only one cell.

EDIT

Ok, here is a method to remove the blue class and add it to the one which was clicked:

// Remember el.attachEvent('onclick', ...) for IE8 and lower

base.addEventListener('click', function delegate(e){

var cells = tbody.getElementsByClassName('blue'),

i = 0,

cell;

while (cell = cells[i++]) {

cell.className = cell.className.replace(/\bblue\b/g, '');

}

e.target.className += ' blue';

});

This uses el.getElementsByClassName(), which is supported by most modern browsers and IE9 and greater. An alternative, of course, could be to do another tbody.getElementsByTagName('td'), which is universally supported.

EDIT 2

Note, I noticed sometimes it's possible not to click a TD, so we should first check for that and ignore the click on table if it's not a td:

base.addEventListener('click', function delegate(e){

var cells = tbody.getElementsByClassName('blue'),

i = 0,

cell;

if (e.target.nodeName.toLowerCase() == 'td') {

while (cell = cells[i++]) {

cell.className = cell.className.replace(/\bblue\b/g, '');

}

e.target.className += ' blue';

}

});

HTML

Javascript

var base = document.getElementById('base'),

tbody = base.getElementsByTagName('tbody')[0],

numrows = 30,

numcols = 10,

col = 0,

row = "

{row}",

rows = "",

cell = "

{cell}",

cells = "";

// Remember el.attachEvent('onclick', ...) for IE8 and lower

base.addEventListener('click', function delegate(e){

e.target.style.backgroundColor = 'blue';

});

while (numrows--) {

cells = "";

col = 0;

while (col++ < numcols) {

cells += cell.replace('{cell}', col);

}

rows += row.replace('{row}', cells);

}

tbody.innerHTML = rows;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值