单击td中的img时更改tr背景颜色

时间:2014-05-03 23:46:14

标签: javascript jquery html css

我正在填充一个带有来自DB

的值的php表

我试图但不成功的是在点击图像时更改tr背景颜色

这是我试图做的事情

<script>
 function changeColor(tr)
 {
   var tableRow = document.getElementById(tr);
   tableRow.style.backgroundColor='red';
 }
</script>

<html>
      <table>
            <tr id='tr<?php echo $personID;?>'>
                  <td>
                      <?php echo $personName;?>
                  </td>
                  <td>
                      <?php echo $personLastName;?>
                  </td>
                  <td>
                      <img src= "/*an image*/" onmouseover="" style="cursor: pointer;" onclick="changeColor('tr<?php echo $personID;?>')" >
                  </td>
            </tr>
      </table>
</html>
很明显,这只是针对一个案例,但是当我从DB获取元素时,这个表很长 任何想法?

感谢提前

还有一件事

我的桌子已经有一个css设计

td
{
 background: #EDEDED;
}
tr:hover
{ 
 background: #d0dafd;
}

这可能是做onclick="this.parentNode.parentNode.style.background='gray'"

时的原因

无法解决这个怎么办?

2 个答案:

答案 0 :(得分:1)

您可以简单地使用parentNode: DEMO

  <img src="http://dummyimage.com/50x50"
       onmouseover="this.parentNode.parentNode.style.background='gray'" 
       onmouseout="this.parentNode.parentNode.style.background=''"
  />

img-&gt; parentNode = td - &gt; parentNode = TR

答案 1 :(得分:0)

jQuery代码

//code for clicks
$('td img').click(function() {
  $(this).closest('table').children('tr').removeClass('highlight');
  $(this).closest('tr').addClass('highlight');
});

//code for hovering
$('tr').hover(function() {
  //if the tr has the highlight class do nothing, otherwise add hover style
  if(!$(this).hasClass('highlight')) {
    $(this).addClass('hoverStyle');
  } 
}, function() {
  //if the tr has hover style remove it when hover ends
  if($(this).hasClass('hoverStyle')) {
    $(this).removeClass('hoverStyle');
  }
});

然后只需创建一个CSS类来定义高亮样式。

相关问题