代码之家  ›  专栏  ›  技术社区  ›  Hani Q

jquery,将td文本赋给变量并发布它

  •  0
  • Hani Q  · 技术社区  · 16 年前

    我对javascript比较陌生,有问题,希望你能帮助我。

    我要做的是

    $("tr:not(:first-child)").each(function(){
                                var sitename = $("this" + "td:nth-child(1)").text();
                                var type= $("this" + "td:nth-child(2)").text();
                                var address= $("this" + "td:nth-child(3)").text();
                                var city= $("this" + "td:nth-child(4)").text();
                                var lat= $("this" + "td:nth-child(5)").text();
                                var long= $("this" + "td:nth-child(6)").text();
                                var ftime= $("this" + "td:nth-child(7)").text();
                                $.post('./watchdog.php',{ oadata: sitename});
                        }).end().remove();
    

    我在表格中选择“tr”,除了第一个包含“th”的表格。然后,我只是剥离td并将文本值赋给变量。最后,我将把这些数据发布到一个PHP脚本中,该脚本基本上将这些数据插入到mysql数据库中。问题是我一直在数据库中获取空值。

    这是在HTML中生成的表

    Site Name   Type    Address City    Lat Long    Fault Time
    ISB056  Spur    Opposite Plot No. 435, Sector I-10/4    Islamabad   73.04393    33.64677    12:02 PM
    ISB078  Spur    SEECS NUST H-12 Islamabad   Islamabad   72.990044   33.64246    12:02 PM
    
    2 回复  |  直到 9 年前
        1
  •  0
  •   Felix Kling    16 年前

    这个

    $("this" + "td:nth-child(1)").text()
    

    生成选择器 thistd:nth-child(1) 这完全没有道理。我想你想要:

    $(this).find("td:nth-child(1)").text()
    

    但更简单的方法是使用

    var data = $(this).children('td').map(function() {
                     return $(this).text();
               }).get();
    

    然后像这样发送数据

    $.post('./watchdog.php',{ sitename: data[0], type: data[1],...});
    
        2
  •  0
  •   jantimon    16 年前

    你不会使用 'this' 但是 this 所以去掉你的引言。

    你也应该使用类。

    <tr class="site">
       <td class="sitename">...</td>
       ...
    </tr>
    

    这将使代码更易于阅读和调试:

    $("tr.site").each(function(){
        var sitename = $(".sitename",this)
    })