单击HTML按钮更改行的背景颜色

HTML button click change the background color of the row

本文关键字:背景 颜色 HTML 按钮 单击      更新时间:2023-09-26

我有一个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";