HTML DOM更改Parent元素的样式

时间:2017-11-10 12:38:07

标签: javascript html css

function cross() {
  var dik = document.getElementsByName('r1c1')[0].parentNode;
  dik.style.color = "red";
}
<table>
  <tr>
    <td><input type="radio" name="r1c1" value="TRUE"></td>
    <td><input type="radio" name="r1c1" value="FALSE"></td>
  </tr>

  <tr>
    <td><input type="radio" name="r1c2" value="TRUE"></td>
    <td><input type="radio" name="r1c2" value="FALSE"></td>
  </tr>

  <input type="button" name="sbmt" value="CHECK" onclick="cross();">

</table>

当我点击按钮时,我想将 td 块的颜色更改为包含的红色 输入元素<input type="radio" name="r1c1" value="TRUE">

4 个答案:

答案 0 :(得分:5)

您必须使用属性backgroundColor来更改td的颜色。 color用于更改text

的颜色

Read Here color vs backgroundColor

<script type="text/javascript">
function cross(){
    var dik = document.getElementsByName('r1c1')[0].parentNode;
    dik.style.backgroundColor = "red";
}
</script>

<table>
<tr>
    <td><input type="radio" name="r1c1" value="TRUE"></td>
    <td><input type="radio" name="r1c1" value="FALSE"></td>
</tr>

<tr>
    <td><input type="radio" name="r1c2" value="TRUE"></td>
    <td><input type="radio" name="r1c2" value="FALSE"></td>
</tr>

<input type="button" name="sbmt" value="CHECK" onclick="cross();">

</table>

答案 1 :(得分:4)

您需要使用backgroundColor而不是颜色:

<script type="text/javascript">
  function cross() {
    var dik = document.getElementsByName('r1c1')[0].parentNode;
    dik.style.backgroundColor = "red";
  }
</script>

<table>
  <tr>
    <td><input type="radio" name="r1c1" value="TRUE"></td>
    <td><input type="radio" name="r1c1" value="FALSE"></td>
  </tr>

  <tr>
    <td><input type="radio" name="r1c2" value="TRUE"></td>
    <td><input type="radio" name="r1c2" value="FALSE"></td>
  </tr>

  <input type="button" name="sbmt" value="CHECK" onclick="cross();">

</table>

答案 2 :(得分:3)

尝试使用17+3代替backgroundColor

color

color is change the text of color not background-color

dik.style.backgroundColor = "red";
function cross() {
  var dik = document.getElementsByName('r1c1')[0].parentNode;
  dik.style.backgroundColor = "red";
}

答案 3 :(得分:1)

您需要设置元素的背景颜色以使其变为红色。

dik.style.background = "red";