在html表格的每一行上添加点击功能

时间:2018-02-22 23:30:55

标签: html python-3.x pandas

我最近创建了一个函数,它根据用户对网站的输入执行一些复杂的名称匹配,并以表格格式将结果作为html文件返回。我的问题是如何在每行添加点击功能?

.Copy

Idea是用户类型的名字,(如果他拼错了,程序建议使用以下名称。因此,表格以html格式返回。

现在我想在每一行添加点击功能。点击希望重新查询我内部的数据库并返回正确的信息。它必须是动态的。这样,我的意思是如果返回一行,您只能单击一行。如果返回10行,您应该可以单击任何行。谢谢

编辑:根据下面的答案,我添加了以下几行,但仍然无法点击该行。不确定我做错了什么。

示例html文件

df = get_cust_info()  # returns a pandas dataframe
df.to_html('results.html')  #converts the dataframe to html

编辑2:在进一步搜索另一个stackoverflow问题时,我尝试将其添加到底部。

    <table border="1" class="dataframe">
     <thead>
     <tr style="text-align: right;"><th></th>
     <th>CustomerName</th>
     <th>firstName</th>
    <th>MiddleName</th>
    <th>LastName</th>
    <th>Address</th>
    <th>zip</th>
    <th>State</th>
    <th>score_first</th>
    <th>score_second</th>
    <th>score_third</th>
    </tr>
   </thead>
   <tbody>
<tr>
  <th>5046</th>
  <td>JAMES G STAHL</td>
  <td>JAMES</td>
  <td>G</td>
  <td>STAHL</td>
  <td>4090 BECK RD</td>
  <td>44256</td>
  <td>OH</td>
  <td>0.97</td>
  <td>1.0</td>
  <td>0.91</td>

<tr>
  <th>5050</th>
  <td>JONATHAN STAHL</td>
  <td>JONATHAN</td>
  <td>None</td>
  <td>STAHL</td>
  <td>4114 BECK RD</td>
  <td>44256</td>
  <td>OH</td>
  <td>0.57</td>
  <td>NaN</td>
  <td>0.91</td>
</tr>
   </tbody>
   </table>

仍然无法正常工作。对不起我是javascript / jquery的新手。如果有人可以帮助那将是一个巨大的帮助

2 个答案:

答案 0 :(得分:2)

答案是在JavaScript中使用event.target。您可以向表本身添加事件侦听器,然后在事件侦听器内部检测实际在其中单击的元素。这样的事情应该有效:

document.querySelector(".dataframe").addEventListener("click", function(e) {
    var row = e.target;
    while (row.matches && !row.matches("tr")) {
        row = row.parentNode;
    }
    if (row.matches && row.matches("tr") { // check for row.matches because at the very top of the document tree row.matches will be undefined but row itself will be non-null
        // This is the table row element you're looking for
    }
});

答案 1 :(得分:0)

我设法通过执行以下操作使行可以点击:我希望它可以帮助社区,因为我在这里找到的一些答案并没有帮助。

<script>
function addRowHandlers() {
var table = document.querySelector(".dataframe");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
    var currentRow = table.rows[i];
    var createClickHandler = 
        function(row) 
        {
            return function() { 
                                    var cell = row.getElementsByTagName("td")[0];
                                    var id = cell.innerHTML;
                                    alert("id:" + id);
                             };
        };

    currentRow.onclick = createClickHandler(currentRow);
    }
}
window.onload = addRowHandlers();
</script>