获取每个不工作的tr的id

Getting the id of each tr not working

本文关键字:tr id 工作 获取      更新时间:2023-09-26

获取表中tr的id的代码不工作。

我从mysql数据库中检索表的数据并填充表。但为了更好更容易阅读,让我们假设我有这样一个表:

<table>
   <tr id = "1" class = "tablerow">
      <td> Your awesome </td>
   </tr>
   <tr id = "2" class = "tablerow">
      <td> Your great </td>
   </tr>
   <tr id = "3" class = "tablerow">
      <td> Your amazing </td>
   </tr>
</table>

还有js:

    $(".tablerow").click(function(event){
        var id = this.id;
        alert(id);
    });

但它不起作用,它只是警告一个空字符串。为什么?

尝试将代码更改为next

$(".tablerow").click(function(event){
    var clicked = $(this),
        id;
    if(clicked.attr('id')){
        id = clicked.attr('id');          
    }
    else{
        id = clicked.parent().attr('id');
    }
    alert(id);
});

假设您的页面上只有一个表:

document.getElementsByTagName("tr")[index].id;

最好是给表一个id,然后得到这样的行:

<table id="tableId">
   <tr id = "1" class = "tablerow">
      <td> Your awesome </td>
   </tr>
   <tr id = "2" class = "tablerow">
      <td> Your great </td>
   </tr>
   <tr id = "3" class = "tablerow">
      <td> Your amazing </td>
   </tr>
</table>

js代码:

var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);

你应该使用

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

解释

当你试图在click事件中访问this时,你只访问元素,但你想选择那个DOM元素,所以你应该使用

$(this) //it will select the DOM element as a Jquery object.

然后你应该使用Jquery的attr方法来访问特定DOM元素的属性

你应该使用:

$(".tablerow").click(function(e) {
   var proxy = this.id;
   id = this.id;
   console.log(id);
});

试试下面的代码,希望对你有所帮助:

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

如果它仍然不工作,尝试检查你的jquery是否被声明。像这样:<script src="../js/jquery-1.11.1.min.js"></script>

享受吧!