开发者

pass var to function() js with jquery

Just looking for the best practise way of doing this. I have a table listing information and in the last column is a button with "Edit/View". When the user clicks on the button a div area appears with more information which can be edited

Code below with some fragments of jstl

<script type="text/javascript">
//Click on Edit/View on table
$('.viewCustomer').click(function()
{
    .......
});

</script>

<tr class="odd">
  <td>${cus开发者_运维问答tomerBean.comName}</td>
  <td>${customerBean.comCode}</td>
  <td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
</tr>

So my question would be:

(1) how do i pass a variable to function $('.viewCustomer').click(function()

(2) is this the best way of going about to do this. Is there a more efficient/secure/cleaner of doing this?

Cheers Alexis


The click function will not be called by you. It is called when the button is clicked, and as such has the event object passed to it:

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

What exactly are you wanting to pass? You can access the DOM element that you are clicking using this and $(this), so maybe it possible to reference what you want from here.

EDIT For comment

if the user clicked on the button that was in the 4th row of the table and in that row the another colum had customer id 1234 i want to pass the variable 1234.

NOTE: None of the below has been tested, but ought to suffice

Let's assume your 'customer id' column has a classname of 'customerid'. So your HTML might be:

<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>

The jQuery might look something like:

$('.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();
});

The above is proken down into lines to show you how stuff is being retrieved. Using 'chaining' we can express it more concisely:

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

You can also search for the customerid cell as a 'sibling' of the button cell for an even more concise approach (and one less function call).

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜