代码之家  ›  专栏  ›  技术社区  ›  roh

JQuery,表单元格上的事件冒泡。如何计算单击了哪一行

  •  1
  • roh  · 技术社区  · 17 年前

    我有一张桌子,里面有一个看起来像这样的div。。。。。。。

    <div id="records">
    
    10 | text1 | Delete
    23 | test2 | Delete
    24 | text3 | Delete
    32 | text4 | Delete
    
    </div>
    

    我想让“Delete”可以点击,它调用一个ajax脚本将它们从数据库中删除。

    这个表是由一个ajax脚本填充的,所以为了避免重新绑定问题,我想在“records”上使用事件冒泡,所以我在div“records”上添加了一个click事件,在这里我检查了“delete\u record”,目前只有一个警报,似乎可以工作。。

    $('#records').click(function(event)  {
        if ($(event.target).is('.delete_record'))  {
            alert("clicked on CELL");
        }
    });
    

    但是我真正想要的是访问ajax脚本知道的记录id,并将其传递给ajax脚本以删除该记录。 我知道如何用正确的值调用这个ajax脚本,但我不知道如何获得这个记录id

    10 | text1 | Delete(20389)
    23 | test2 | Delete(37474)
    24 | text3 | Delete(2636)
    32 | text4 | Delete(83731)
    

    所以当我点击第二行时,脚本会调用。。。。

    $.getJSON("/ajax/delete_record.php",{id: 37474, ajax: 'true'}, function(j){ stuff }
    
    1 回复  |  直到 17 年前
        1
  •  2
  •   xandy    17 年前

    您说过该表是从ajax填充的,因此,您实际上可以将元数据存储到该表中,假设生成了以下html:

    <tr>
        <td>23</td>
        <td>test2</td>
        <td><a>Delete</a></td>
        <td class='id'>37474</td> <!-- Hide the id column in css if needed -->
    </tr>
    

    所以,为了跟随你所做的,如果你点击了“单元格”,那么你只需返回到它的父级,然后查找td.hasClass类('id')并获取其中的文本。比如:

    var parentTR = $(event.target).parent('tr'); // Get the parent row
    var id = $("td[class='id']", parentTR).html(); // Retrieve the id content
    

    现在你有了这个id,你就可以用ajax把它放到服务器上删除它。

    还有一件事要补充,我不太同意表上的事件绑定或父div来定位delete按钮,这听起来太间接了。JQ其实提供了一个很好的方法来实时绑定事件,试试看 Live Function in JQuery . 它实际上对你的处境有好处。