简体   繁体   English

Javascript HTML Table根据另一个单元格的onclick获取第一列的单元格值

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

I am making a PHP web application and fetching data from MySql into the HTML table below. 我正在制作一个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>

Here is the output of the table 这是表的输出

在此处输入图片说明

The third column consists of clickable image icons which loads question papers in an iFrame besides it. 第三列由可点击的图像图标组成,该图标可将问题纸加载到iFrame中。

I want that when this image is clicked, the cell value of the first column --> 'Subject code' for that particular row is obtained. 我希望单击此图像时,获得该特定行的第一列->“主题代码”的单元格值。

Here is the code: 这是代码:

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*/;  
}

I require this subject code value as one of the variables in the pdf src path of the iFrame. 我需要将此主题代码值作为iFrame的pdf src路径中的变量之一。

But nothing seems to be working, the value in 'v' variable is showing undefined. 但是似乎没有任何作用,'v'变量中的值显示为未定义。

How can I make this code work? 如何使此代码起作用?

you need to use onclick() event to get value of Subject_Code . 您需要使用onclick()事件获取Subject_Code值。

Change 更改

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

With

<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>

And your showPaper() should be 并且您的showPaper()应该是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM