![](/img/trans.png)
[英]Change a specific TD's background color on click button with JavaScript/ajax
[英]How do I change a specific TD's background color on click with JavaScript/jQuery?
我有一個<td style="background-color:white"></td>
。
我想這樣做,以便當我在該td
內單擊時,背景顏色變為黑色。 如何使用 jQuery 完成此任務? 是 onmousedown 事件還是 click 事件?
使用正常的 JavaScript 我試過:
<td style="background-color:white" onclick="$(this).onmousedown('background-color','black')">SomeText</td>
......但它沒有工作......
嘗試這個...
$('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);
后面的示例僅綁定一個事件處理程序。
添加 class 可能會更好,因此您可以在樣式表中指定 styles,而不是耦合您的表示層和行為層。
$('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 object 上沒有onmousedown()
事件(盡管有mousedown()
)。
正確的 function 是mousedown 。 但是您可以只使用click 。
<table> ... </table>
<script>
$("table tr td").click(function() {
$(this).css("background", "#fff");
});
</script>
建議您的腳本不要與 HTML 混合,但這是有效的:
<table>
<tr>
<td onclick="$(this).css('background', '#fff')">change color</td>
</tr>
</table>
您的 onclick 事件正在嘗試(不正確的語法)在自身上綁定一個事件並且它沒有改變元素樣式。
.bind
或.click
將綁定到現有元素, live
將綁定到任何元素,即使它是在之后插入的。
jQuery 參考資料
我認為 jquery 在這里可能有點矯枉過正。 你可以使用這樣的東西。
<table>
<tr>
<td onclick="javascript:this.style.background = '#000000';">this</td>
</tr>
</table>
你可以在這里玩 - http://jsfiddle.net/yVvyg/
這也可以從頭部標簽開始
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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.