簡體   English   中英

從表的td獲取id

[英]Get id from td of a table

<script type="text/javascript">
function LoadData(){   
    var url = serverURL+"/List.php";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function(data){    
            $.each(data.data, function (key, value) {
                var doc_id=value['id'];
                var doc_name=value['name'];
                var doc_speci = value['specialize'];
                $("#myTable").append("<tr><td>"+doc_name+"</td><td>"+doc_speci+"</td><td class='retrieve' data-did="+doc_id+" style='cursor: pointer;'>EDIT</td></tr>");                    
            });
        },
        error: function(data){
            toastr.error("Opps! Something went wrong");
            $(".se-pre-con").fadeOut("slow");
        },
    });
}
</script>

以上將tr添加到下面的html表中。 HTML TABLE如下:

<table id="myTable" class='table table-bordered table-hover table-striped'>
    <tr>
        <th>Name</th>
        <th>Specialization</th>
        <th>Action</th>
    </tr>
</table>

現在我想從td類檢索數據屬性中檢索id,這樣我就可以發送id並將其重定向到其他頁面進行編輯。

首先,要添加數據屬性,應確保在值周圍添加引號:

data-did='"+doc_id+"'...

因此,渲染單元必須是這個樣子:

<td class='retrieve' data-did='n' style='cursor: pointer;'>EDIT</td>

(其中n是某個值)

然后,您可以使用jQuery輕松檢索此值:

$('specific-td').data('did'); //specific-td referes to a specific cell in a row, you must write that, this is just an example

獲取所有行:

var ids = [];
$('.retrieve').each(function() {
    ids.push($(this).data('did'));
});

示例:如果您有一個按鈕,例如:

$('#myTable').on('click', '.retrieve input[type="button"]', function() {
    var id = $(this).parent().data('did');
    alert(id);
});

JSFiddlehttps//jsfiddle.net/y2an0fu7/1/

// Clicks the edit field
$("td.retrieve").on("click", function(e) {

    var id = $(e.currentTarget).attr("data-did");

    // do with the ID what you want
    alert(id);

});

我知道jQuery有一個“數據(...)”功能,但我有時會遇到問題。 “attr(...)”將執行類似的操作,但特別依賴於屬性而不是存儲的對象。

暫無
暫無

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

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