【问题标题】:How to find table tr with ID that match json key and populate other column如何查找 ID 与 json 键匹配的表 tr 并填充其他列
【发布时间】:2012-10-03 10:19:07
【问题描述】:

我是 JQuery 和 Json 的新手,遇到了一些问题。如果有人可以为我提供一些帮助,将不胜感激。我的问题如下:

在我的 JSP 中,我有 ajax 调用,它将返回我的 json 对象。我想在我的 json 对象中获取键,在我的表中找到其 ID 与键匹配的那些 tr,并最终用我的 json 对象中的值填充该特定行中的其他列。

这是我的 jquery ajax 调用

    $.ajax({
....
....
success:function(data) {    
//Data is a Json Object. The value is for example :{"A":"1","B":"2","C":"3"}    
for(key in data) {
    $("#myTable tr").find(key).find("td").eq(1).html(data[key]); // not working!
}
}
});

,我有以下 html 块:

<table id = "myTable">
    <tr id = "A">
      <td>Descriptopn.</td>
 <td>...</td> // I want to set this value to be 1
    </tr>

    <tr id = "B">
 <td>Description</td>
 <td>...</td> // I want to set this value to be 2
    </tr>

     <tr id = "C">
  <td>Description</td>
       <td>...</td> // I want to set this value to be 3
</tr>   
 </table> 

我的问题是上面的语法不起作用。有没有办法让这件事变得正确?谢谢。

【问题讨论】:

    标签: jquery ajax json jsp


    【解决方案1】:

    .find() 在每个匹配的元素中搜索与给定选择器匹配的后代。由于您要搜索表的后代,而不是行的后代,因此请去掉原始选择器中的 tr。然后,在 key 前面加上 '#' 标记,使其成为有效的 id 选择器,其余部分将按预期工作。

    for(var key in data) {
        $("#myTable").find('#'+key).find("td").eq(1).html(data[key]); // working!
    }
    

    【讨论】:

    • @Ryan 没问题,很高兴为您提供帮助!如果这解决了您的问题,请接受答案(通过单击帖子左侧的淡出复选标记,在投票计数器下方):)
    【解决方案2】:

    既然你有id(它应该是唯一的!),你可以使用以下:-

    $('#' + key).find('td:eq(1)').text(data[key]);
    

    Here's a fiddle

    【讨论】:

    • 谢谢!有用!而且比我之前的方法效率高很多!
    【解决方案3】:
    $.each(data, function(i, val){
    
         $('#myTable tr#' + i).find('td:last').text(val);
     });
    

    【讨论】:

      猜你喜欢
      • 2022-12-03
      • 2020-12-30
      • 2012-03-15
      • 2022-01-12
      • 2013-03-23
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 2021-09-29
      相关资源
      最近更新 更多