簡體   English   中英

單擊td中的img時更改tr背景顏色

[英]Change tr background color when img inside td is clicked

好吧,我用來自數據庫的值用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>

顯然,這只是一種情況,但是當我從數據庫中獲取元素時,該表就很長了
有任何想法嗎?

提前致謝

還有一件事

我的桌子已經有一個CSS設計

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

這也許就是為什么在進行onclick="this.parentNode.parentNode.style.background='gray'"

無法正常工作,我該如何解決?

您可以簡單地使用parentNode: DEMO

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

img-> parentNode = td-> parentNode = tr

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類來定義突出顯示樣式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM