簡體   English   中英

如何在jquery和javascript中檢索html標簽屬性?

[英]How to retrieve the html tag attributes in jquery and javascript?

我嘗試了以下代碼從數組繪制表並從行中檢索屬性ID。 任何建議將不勝感激。

$(document).ready(function(){

$.get('php/php.php', function(data){
    $.each(data, function(index, value){
    $('table').append(
        "<tr id='someid'>"
            +"<td>"+value.ticker+"</td>"
            +"<td>"+value.bid+"</td>"
        +"</tr>");
    }); 
}, "json");

$('tr').click(function(){
var id = $(this).attr("id");
alert(id);

}) 

}); 

您將單擊事件綁定到尚不存在的元素,因為它們是在異步回調中構造的。 代替click ,使用on 由於您的表不是動態構造的,因此可以將on處理程序附加到該表。

$('table').on('click', 'tr', function () {
    ...
});

http://api.jquery.com/on/

另外,您正在生成多個具有相同ID的<tr> 那不是有效的標記。

由於您是向DOM動態注入新內容,因此它不會知道您綁定的click事件。 因此您的點擊事件將無法正常運行。

解決方案: on使用jQuery

$(document).on("click","tr",function(){
  var id = $(this).attr("id");
  alert(id);
}) 

此方法可從jQuery 1.7+版本開始使用。 如果您使用的是舊版本,則可以考慮使用委托

從jQuery 1.7開始,不推薦使用.live().delegate()方法。 使用on方法。

一切都很好,但是您在tr click事件結束時剛剛錯過了分號

$('tr').click(function(){
    var id = $(this).attr("id");
    alert(id);
});

如果tr id是唯一的,這將通知tr的id

確保在任何語法錯誤中都不允許執行jquery代碼。

暫無
暫無

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

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