簡體   English   中英

Javascript HTML Table根據另一個單元格的onclick獲取第一列的單元格值

[英]Javascript HTML Table get first column's cell value based on another cell's onclick

我正在制作一個PHP Web應用程序並將數據從MySql提取到下面的HTML表中。

<table id = "table" width="500px" cellpadding=2 celspacing=5 border=2 >
 <tr>
   <th>Subject Code</th>
   <th>Subject Name</th>
   <th>Question Paper</th>
 </tr>
 <?php while($row=mysqli_fetch_array($result)):?>
 <tr>
   <td align="center"><?php echo $row['Subject_Code'];?></td>
   <td align="center"><?php echo $row['Subject_Name'];?></td>
   <td align="center"><a href="javascript:showPaper()"><img border="0" alt="image" src="ProjectPictures/questionPaper.png" width="30" height="30"></a></td>
 </tr>
 <?php endwhile;?> 
</table>

這是表的輸出

在此處輸入圖片說明

第三列由可點擊的圖像圖標組成,該圖標可將問題紙加載到iFrame中。

我希望單擊此圖像時,獲得該特定行的第一列->“主題代碼”的單元格值。

這是代碼:

function showPaper(){
   var v;
   //method1 not working
   for(var i=1;i<table.rows.length; i++){
      table.rows[i].onclick = function(){
        rIndex = this.rowsIndex;
        v=this.cells[0].innerHTML;
        alert(v);
      };
   }
  //method 2 not working
  v = $("#table tr.selected td:first").html(); 
  alert(v);            
  /*loc1 path rest of code
  document.getElementById('myiFrame').src = loc1*/;  
}

我需要將此主題代碼值作為iFrame的pdf src路徑中的變量之一。

但是似乎沒有任何作用,'v'變量中的值顯示為未定義。

如何使此代碼起作用?

您需要使用onclick()事件獲取Subject_Code值。

更改

<td align="center"><a href="javascript:showPaper()"><img border="0" alt="image" src="ProjectPictures/questionPaper.png" width="30" height="30"></a></td>

<td align="center" id="<?php echo $row['Subject_Code'];?>" onclick="showPaper(this.id);"><img border="0" alt="image" src="ProjectPictures/questionPaper.png" width="30" height="30"></td>

並且您的showPaper()應該是

<script>
    function showPaper(id)
    {
        alert(id);
        //Do something
    }
</script> 

暫無
暫無

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

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