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

使用jquery将var传递给函数()js

  •  2
  • alexis  · 技术社区  · 14 年前

    只是在寻找最好的实践方法。 我有一个表列表信息,在最后一列中是一个带有“编辑/查看”的按钮。当用户单击按钮时,会出现一个DIV区域,其中包含可编辑的更多信息。

    下面的代码包含一些JSTL片段

    <script type="text/javascript">
    //Click on Edit/View on table
    $('.viewCustomer').click(function()
    {
        .......
    });
    
    </script>
    
    <tr class="odd">
      <td>${customerBean.comName}</td>
      <td>${customerBean.comCode}</td>
      <td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
    </tr>
    

    所以我的问题是:

    (1)如何将变量传递给函数$('.viewCustomer')。单击(函数())

    这是最好的方法吗?是否有更有效/更安全/更清洁的方法?

    干杯 亚历克西斯

    1 回复  |  直到 14 年前
        1
  •  2
  •   Mutation Person    14 年前

    您将不会调用click函数。当单击按钮时调用它,因此事件对象传递给它:

    $('.viewCustomer').click(function(evt){
        .......
    });
    

    你到底想通过什么?您可以使用 this $(this) 所以也许可以从这里引用你想要的东西。

    编辑以供评论

    如果用户单击了 在桌子的第四排 另一只小马的那一排 客户ID 1234我想通过 变量1234。

    注:以下各项均未试验,但应满足要求。

    假设您的“客户ID”列的类名为“customer id”。所以您的HTML可能是:

    <tr class="odd">
      <td>${customerBean.comName}</td>
      <td class="customerid">${customerBean.comCode}</td>
      <td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
    </tr>
    

    jQuery可能看起来像:

    $('.viewCustomer').click(function(){
        var $buttonCell = $(this).parent(); //the <td> containing the button
        var $buttonRow = $buttonCell.parent(); //the <tr> containing the button and your customer id
        var $customerIdCell = $buttonRow.find("td.customerid");
        var customerId = $customerIdCell.text();
    });
    

    上面的内容被翻成一行,向您展示如何检索资料。使用“链接”我们可以更简洁地表达它:

    $('.viewCustomer').click(function(){
        var customerId = $(this).parent().parent().find("td.customerid").text();
    }
    

    您还可以将customerid单元格作为按钮单元格的“兄弟”搜索,以获得更简洁的方法(以及更少的函数调用)。

    $('.viewCustomer').click(function(){
        var customerId = $(this).parent().siblings("td.customerid").text();
    }