我有一个< td style =“background-color:white”>< / td> ;. 我想要这样做,当我点击里面的td,背景颜色变成黑色.如何用jQuery完成这个?这是一个过时的事件还是点击事件? 使用正常的
JavaScript我试过:
@H_502_2@<td style="background-color:white" onclick="$(this).onmousedown('background-color','black')">SomeText</td>
…但它没有工作…
解决方法
尝试这个…
jQuery的
@H_502_2@$('td').click(function() { $(this).css('backgroundColor','#000'); });…要么….
@H_502_2@$('table').on('click','td',function() { $(this).css('backgroundColor','#000'); });JavaScript的
@H_502_2@[].forEach.call(document.getElementsByTagName('td'),function(item) { item.addEventListener('click',function() { item.style.backgroundColor = '#000'; },false); });…要么…
@H_502_2@var table = document.getElementsByTagName('table')[0]; var changeStyle = function(e) { if (e.target.tagName == 'td') { e.target.style.backgroundColor = '#000'; } }; table.addEventListener('click',changeStyle,false);后面的例子只绑定一个事件处理程序.
添加一个类可能会更好,因此您可以在样式表中指定样式,而不是将演示文稿和行为层相结合.
jQuery的
@H_502_2@$('td').click(function() { $(this).addClass('active'); );…要么….
@H_502_2@$('table').on('click',function() { $(this).addClass('active'); });CSS
@H_502_2@td.active { background: #000; }这不行的原因…
@H_502_2@<td style="background-color:white" onclick="$(this).onmousedown('background-color','black')"> SomeText </td>…是因为jQuery对象没有onmousedown()事件(虽然有mousedown()
).