单击HTML按钮更改行的背景颜色
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>
你能帮我做这个吗?谢谢
您应该使用class,为了更好地练习,请删除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';
http://jsfiddle.net/cguLU/1/
要重置表中的其他行,请执行:
http://jsfiddle.net/cguLU/2/
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";
相关文章:
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何使用jquery更改html中的背景颜色
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- JS幻灯片与CSS背景颜色变化
- DT数据表背景颜色为黑色,但仍有悬停和选择颜色
- Javascript通过列表项的函数和css来更改背景颜色
- Javascript没有从数组中选择背景颜色
- 使用圆中的数组更改背景颜色项目
- 如何用jquery动画改变背景颜色,就像一个过渡
- 使用jquery交换并保存背景颜色
- j查询如何设置/取消设置下拉菜单的背景颜色
- 使用angularjs根据时间更改背景颜色
- 设置Dojo量表的背景颜色
- javascript样式的背景颜色在设置时闪烁.ASP.NET
- 使用javascript更改任意文本的背景颜色
- 在用Javascript更改背景颜色后:hover don'不要改变颜色
- 图像内部的透明背景颜色不受影响
- jQuery mobile-动态更改ui页面背景颜色
- 切换按钮的背景颜色
- JavaScript更改类的背景颜色