【问题标题】:Getting table elements in same row with jquery使用jquery获取同一行中的表格元素
【发布时间】:2023-03-06 11:06:01
【问题描述】:

我真的很困惑如何做到这一点。选择一个时,我需要获取两个<td> 的值。例如,下面假设我选择 id=monthly 550 美元的 td。我需要得到与该价格相对应的年龄和超额。我希望这是有道理的。所以在选择 $550 的示例中,我需要 jQuery 来获取值 age(18-24) 和excess($1000)。然后我将把这两个值插入到 mysql 中,如下所述。无论如何我可以用jQuery或PHP做到这一点吗?我对想法持开放态度。

<table>
    <tr>
    <td width="67"></td>
    <td width="102" id="excess">$1000</td>
    <td width="102" id="excess">$2000</td>
    </tr>
    <tr>
    <td width="67" id="age">18-24</td>
    <td width="102" id="monthly">$550</td>
    <td width="102" id="monthly">$650</td>
    </tr>
    <tr>
    <td width="67" id="age">25-29</td>
    <td width="102" id="monthly">$750</td>
    <td width="102" id="monthly">$850</td>
    </tr>
    </table>

MYSQL(使用上面的例子):

$query = mysql_query("UPDATE table SET Monthly = '$550' WHERE Age = '18-24' AND Excess = '$1000'")or die(mysql_error());

【问题讨论】:

  • 您的 HTML 无效。您不能拥有多个具有相同idid 值的元素(顾名思义)必须是唯一的。如果您尝试对元素进行分类,请使用class

标签: php jquery sql html-table


【解决方案1】:

您的 HTML 无效。不能有多个具有相同idid 值的元素(顾名思义)必须是唯一的。如果您尝试对元素进行分类,请使用class。此答案的其余部分假定那些 id 值已更改为 class 名称。

如果我理解您的意思,您希望使用 monthly 类处理对单元格的点击,并获取行中第一个单元格的文本以及列中的第一个单元格。这可以通过 jQuery (live example | source) 轻松完成:

$("td.monthly").click(function() {
    var $this = $(this),
        firstCellInRow = $this.closest('tr').find('td').first(),
        firstCellInColumn = $this.closest('table').find('tr').first().find('td').eq($this.index());
    console.log("First cell in row: " + firstCellInRow.text());
    console.log("First cell in column: " + firstCellInColumn.text());
});

我们通过closest 找到行中的第一个单元格,然后通过findfirst 找到它的第一个单元格。

我们通过closest找到表格找到列中的第一个单元格,然后通过findfirst获得第一行,然后获得被点击单元格的index并在通过eq 具有相同索引的第一行。

【讨论】:

  • 你对身份证的看法是对的......我有一个金发碧眼的时刻。这非常有效.. 非常感谢您抽出宝贵时间提供帮助!
【解决方案2】:
$('.monthly').bind('click', function()
{
    lstrMonth  = $(this).html();
    lstrAge    = $(this).parent().find('td:first').html();
    lnIndex    = $(this).parent().index($(this));
    lstrExcess = $(this).parent('table').find('tr:first td:nth-child('+ (lnIndex + 1) +')');

    // do ajax call to a php script which execute the query
    $.post('ajax/update.php', 
    {
        age:    lstrAge,
        excess: lstrExcess,
        month:  lstrMonth  
    },
    function(data) // success
    {
        // do whatever you want
    });
});

我认为这会起作用,PHP 将简化如下:

<?php
    $query = mysql_query("UPDATE table SET Monthly = '".$_POST['month']."' WHERE Age = '".$_POST['age']."' AND Excess = '".$_POST['excess']."'")or die(mysql_error());
?> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2010-09-14
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多