简体   繁体   English

单击时如何在html表格单元格中获取数据?

[英]How to get the data inside a html table cell when clicked on it?

I created a html table and filled it dynamically. 我创建了一个html表并动态填充它。 So I want to alert the data inside a cell of the table when i clicked it. 因此,我想在单击表格的单元格时向其发出警报 Here is the code for the table 这是表格的代码

JSP JSP

<table id="load-opt"></table>

I'm filling the data inside dynamically like this 我这样动态地填充数据

var fillTable = function($element, data) {
    var t_head = $("<tr></tr>");
    for(var ind=0; ind<data.length; ind++) {
        //name is the name and desc is the description for each option
        var $option = $("<tr></tr>");
        $option.html("<td>"+name+"</td><td>"+desc+"</td>");
    }
};

I tried this but it's not working, it's giving "undefined". 我尝试了这个,但是它不起作用,它给出了“ undefined”。

var choice = $('table#load-opt tr td');
choice.click(function(){
    alert(choice); // also tried alerting choice.textContent, choice.innerHTML and choice.firstChild
});

you are actually trying to alert the 'td' object not value of from that object so you can use following to solve the query.Here i am using on instead of direct click function because of dynamically added data. 您实际上是在试图警告该对象的'td'对象而不是值,因此您可以使用以下方法来解决查询。由于动态添加的数据,我在此使用on而不是直接单击功能。

var choice = $('table#load-opt tr td');
 choice.on('click', function(){
 alert($(this).text());
});

You can use $(this).text() to fetch the data in table cell. 您可以使用$(this).text()来获取表单元格中的数据。 This is a link. 这是一个链接。

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

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