簡體   English   中英

單擊時如何在html表格單元格中獲取數據?

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

我創建了一個html表並動態填充它。 因此,我想在單擊表格的單元格時向其發出警報 這是表格的代碼

JSP

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

我這樣動態地填充數據

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>");
    }
};

我嘗試了這個,但是它不起作用,它給出了“ undefined”。

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

您實際上是在試圖警告該對象的'td'對象而不是值,因此您可以使用以下方法來解決查詢。由於動態添加的數據,我在此使用on而不是直接單擊功能。

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

您可以使用$(this).text()來獲取表單元格中的數據。 這是一個鏈接。

暫無
暫無

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

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