如何使用JavaScript / jQuery更改特定TD的背景颜色?

时间:2011-04-29 14:03:04

标签: javascript jquery html css

我有<td style="background-color:white"></td>

我想这样做,当我点击td内部时,背景颜色变为黑色。我如何使用jQuery实现这一目标?是onmousedown事件还是点击事件?

使用普通的JavaScript我尝试过:

<td style="background-color:white" onclick="$(this).onmousedown('background-color','black')">SomeText</td>

......但它不起作用......

3 个答案:

答案 0 :(得分:25)

试试这个......

的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);

后面的示例仅绑定一个事件处理程序。

添加一个类可能更好,因此您可以在样式表中指定样式,而不是将您的演示文稿和行为层结合起来。

的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())。

答案 1 :(得分:3)

正确的功能是mousedown。但您可以使用click

<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/

相关问题