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

时间:2018-04-14 05:33:00

标签: javascript php html html-table

我正在创建一个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>

这是表

的输出

enter image description here

第三列包含可点击的图像图标,除了它之外,它还可以在iFrame中加载问题文件。

我希望在点击此图片时,第一列的单元格值 - &gt; &#39;主题代码&#39;获得该特定行。

以下是代码:

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路径中的变量之一。

但似乎没有任何效果,&#39; v&#39;变量显示未定义。

如何使此代码有效?

1 个答案:

答案 0 :(得分:1)

您需要使用> dput(df) structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L), age = structure(c(2L, 1L, 2L, 2L, 1L, 1L), .Label = c("20-29", "30-39"), class = "factor"), edu = structure(c(1L, 2L, 1L, 1L, 2L, 2L), .Label = c("Primary", "Secondary"), class = "factor"), blood = c(5.5, 8.7, 10, 11, 10, 9)), .Names = c("id", "age", "edu", "blood"), class = "data.frame", row.names = c(NA, -6L)) 事件来获取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()