我有<td style="background-color:white"></td>
。
我想这样做,当我点击td
内部时,背景颜色变为黑色。我如何使用jQuery实现这一目标?是onmousedown事件还是点击事件?
使用普通的JavaScript我尝试过:
<td style="background-color:white" onclick="$(this).onmousedown('background-color','black')">SomeText</td>
......但它不起作用......
答案 0 :(得分:25)
试试这个......
$('td').click(function() {
$(this).css('backgroundColor', '#000');
});
...或....
$('table').on('click', 'td', function() {
$(this).css('backgroundColor', '#000');
});
[].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);
后面的示例仅绑定一个事件处理程序。
添加一个类可能更好,因此您可以在样式表中指定样式,而不是将您的演示文稿和行为层结合起来。
$('td').click(function() {
$(this).addClass('active');
);
...或....
$('table').on('click', 'td', function() {
$(this).addClass('active');
});
td.active {
background: #000;
}
这不起作用的原因......
<td style="background-color:white"
onclick="$(this).onmousedown('background-color','black')">
SomeText
</td>
...是因为jQuery对象上没有onmousedown()
事件(尽管有mousedown()
)。
答案 1 :(得分:3)
<table> ... </table>
<script>
$("table tr td").click(function() {
$(this).css("background", "#fff");
});
</script>
<强> See this example on jsFiddle 强>
建议您的脚本不与HTML混合,但这是有效的:
<table>
<tr>
<td onclick="$(this).css('background', '#fff')">change color</td>
</tr>
</table>
<强> See this example on jsFiddle 强>
您的onclick事件尝试(语法不正确)将事件绑定在自身上并且不会更改元素样式。
<强> This example shows why the same script on the head doesn't work. 强>
.bind
或.click
将绑定到现有元素,live
将绑定在任何元素上,即使之后插入它也是如此。
jQuery引用
答案 2 :(得分:3)
我认为jquery在这里可能有些过分。你可以使用这样的东西。
<table>
<tr>
<td onclick="javascript:this.style.background = '#000000';">this</td>
</tr>
</table>
你可以在这里玩 - http://jsfiddle.net/yVvyg/
这也可以从头部标签中bed <
loadtheclicks() {
var ar = document.querySelectorAll("td"); //could also use getElementByTagname
for (var i=0; i< ar.length; i++) {
ar[i].addEventListener("click", function() { this.style.background = '#000000'; }, false);
}
}
打电话给那个onload,你应该是金牌。我也在jsfiddle上有这个 - http://jsfiddle.net/2anSz/4/