我有一个 <td style="background-color:white"></td>
.
我想做的是当我点击里面的 td
时,背景颜色变为黑色。我如何使用 jQuery 完成此操作?是onmousedown事件还是click事件?
我尝试使用普通的 JavaScript:
<td style="background-color:white" onclick="$(this).onmousedown('background-color','black')">SomeText</td>
...但是没用...
最佳答案
试试这个...
jQuery
$('td').click(function() {
$(this).css('backgroundColor', '#000');
});
……或者……
$('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);
});
……或者……
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);
后面的例子只绑定(bind)一个事件处理器。
添加一个类可能会更好,这样您就可以在样式表中指定您的样式,而不是耦合您的表示层和行为层。
jQuery
$('td').click(function() {
$(this).addClass('active');
);
……或者……
$('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()
)。
关于javascript - 如何使用 JavaScript/jQuery 在单击时更改特定 TD 的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5833088/