![](/img/trans.png)
[英]Angular - Change button BackGround Color of Row in Table After click the Button
[英]HTML button click change the background color of the row
我有一個HTML表,每行都有一個按鈕。 這里的目標是當點擊一個按鈕時,整行將改變背景顏色。 代碼是:
<table>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="button" value="press" onclick="myFunction(this)" />
</td>
</tr>
<tr>
<td>Value3</td>
<td>Value4</td>
<td>
<input type="button" value="press" onclick="myFunction(this)" />
</td>
</tr>
</table>
<script type="text/javascript">
function myFunction(e) {
//change the background color of the row
}
</script>
你能幫幫我嗎? 謝謝!
您應該使用類而不是為了良好的練習刪除html中的內聯函數調用。
用這個:
HTML
<table>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="button" value="press" />
</td>
</tr>
<tr>
<td>Value3</td>
<td>Value4</td>
<td>
<input type="button" value="press" />
</td>
</tr>
</table>
jQuery的
var all_tr = $('tr');
$('td input[type="button"]').on('click', function () {
all_tr.removeClass('selected');
$(this).closest('tr').addClass('selected');
});
(更新)
jQuery closest
方法是完美的,因為你在標簽中包含了jQuery
:
function myFunction(el) {
//change the background color of the row
$(el).closest('tr').css('background-color', 'red');
}
在非jQuery方式中,您可以:
function myFunction(el) {
//change the background color of the row
while (el && (el.tagName.toLowerCase() != 'tr'))
el = el.parentNode;
if (el)
el.style.backgroundColor = 'red';
}
你可以使用這些解決方案與jQuery。
<script type='text/javascript'>
$('table input').bind('click', function (e) {
$(this).parent().parent().addClass('redBackground');
});
</script>
創建CSS類,我將其命名為“redBackground”。
<style type='text/css'>
.redBackground {
background: #fff;
}
</style>
問候。
這是你可以做到的一種方式: http : //jsfiddle.net/69sU7/
myFunction = function(btn) {
$(btn).parent().parent().addClass('highlight');
}
當單擊按鈕時,使用jQuery,我們捕獲btn本身,然后獲取其父( td
),並獲取其父( tr
)。 然后我們將類highlight
添加到該tr
。
.highlight
類添加到它下面的所有td
,黃色背景。
使用直接屬性backgroundColor
e.parentNode.parentNode.style.backgroundColor = '#ff0';
要重置表中的其他行,請執行以下操作:
function myFunction(e) {
var tr = e.parentNode.parentNode;
var table = e.parentNode.parentNode.parentNode;
//set current backgroundColor
var len = table.childNodes.length;
for (var i = 0; i < len; i++) {
if (table.childNodes[i].nodeType == 1) {
table.childNodes[i].style.backgroundColor = 'transparent';
}
}
tr.style.backgroundColor = '#ff0';
}
使用這個http://jsfiddle.net/4P3Jb/
e.parentNode.parentNode.style.background = "red";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.