尝试这个...
jQuery
$('td').click(function() {
$(this).css('backgroundColor', '#000');
});
...or....
$('table').on('click', 'td', function() {
$(this).css('backgroundColor', '#000');
});
JavaScript
[].forEach.call(document.getElementsByTagName('td'), function(item) {
item.addEventListener('click', function() {
item.style.backgroundColor = '#000';
}, false);
});
...or...
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
$('td').click(function() {
$(this).addClass('active');
);
...or....
$('table').on('click', 'td', function() {
$(this).addClass('active');
});
CSS
td.active {
background: #000;
}
这个方法无法正常工作的原因是...
<td style="background-color:white"
onclick="$(this).onmousedown('background-color','black')">
SomeText
</td>
这是因为jQuery对象上没有
onmousedown()
事件(尽管有
mousedown()
)。