js实现点击一个按钮,表格中某行变色,按钮的value与表格中列name值相同的行变色

JavaScript07

js实现点击一个按钮,表格中某行变色,按钮的value与表格中列name值相同的行变色,第1张

<table>

  <tr>

    <td name="r1c1">第一行第一列</td>

    <td name="r1c2">第一行第二列</td>

  </tr>

  <tr>

    <td name="r2c1">第二行第一列</td>

    <td name="r2c2">第二行第二列</td>

  </tr>

</table>

<input id="button" type="button" value="r2c1" />

<script>

window.onload = function () {

  document.getElementById('button').onclick = function () {

    var tds = document.getElementsByTagName('td')

    for (var i = 0 i < tds.length i++) {

      var td = tds[i]

      if (td.getAttribute('name') == this.value) {

        td.parentNode.style.backgroundColor = 'red'

      }

    }

  }

}

</script>

为什么要用js呢,这个完全可以用a 标签的css属性来完成的呀。

以下为css代码

a{ } 默认的值

a:link {} /* 未访问的链接 */

a:visited {} /* 已访问的链接 */

a:hover {}/* 当有鼠标悬停在链接上 */

a:active {} /* 被选择的链接 */

<head>

<title>无标题文档</title>

<style type="text/css">

body {

background-color: #CCC

text-align: left

}

body div table tr th {

text-align: left

}

body div table {

font-family: Verdana, Geneva, sans-serif

font-size: 24px

}

.background_c{

background-color: red

}

</style>

</head>

<body>

<div align="center">

  <table width="615" height="157" border="5" align="center">

    <tr>

      <td width="530" height="48">1、      

        <input type="radio" name="radio" id="radio" value="radio" />

        a

        <input type="radio" name="radio" id="radio2" value="radio" /> 

        b

</td>

    </tr>

    <tr>

      <td height="54">2、

        <input type="radio" name="radio3" id="radio3" value="radio3" />

        c

        <input type="radio" name="radio3" id="radio4" value="radio3" /> 

        d

</td>

    </tr>

    <tr>

      <td height="37"><div align="center">

        <input type="submit" name="确认" id="确认" value="确认"  />

      </div></td>

    </tr>

  </table>

</div>

</body>

<script src="jq.js"></script>

<script>

$('table').on('click', 'input[type=radio]', function() {

$(this).parent().addClass('background_c')

})

</script>

</html>