Zbarcea Christian
Zbarcea Christian

Reputation: 9548

jquery passing data from table row to functions

I'm using this method for years and I don't know if this a good idea. How you proceed if you want to pass data to a functions?

For example, passing a string data to jquery .hover event:

<table>...

<tr class='my_row' id='uniqueid_param1_param2_param3'>
   <td>Some value #1</td>
   <td>Some value #2</td>
   ...
   <td>Some value #n</td>
</tr>

And within jQuery:

$('.my_row').hover(function(){
   var param = $(this).attr('id').split('_');

   param[1]; // param1
   param[2]; // param2
   param[3]; // param3
});

There are advantages and disadvantages, I won't enumerate them, but I will write another example how normal people, or how I think others are using:

<table>...

<tr class='my_row'
      onmouseover="handle_param('param1', 'param2', 'param2');"
      onmouseout="handle_param('param1', 'param2', 'param2');">
   <td>Some value #1</td>
   <td>Some value #2</td>
   ...
   <td>Some value #n</td>
</tr>

And within js:

function handle_param(param1, param2, param3){
  //...
}

I don't like this method, if you have many many rows this wouldn't be a good ideea.

So, how do you proceed? How you would do it if you have to pass data to a functions?

Upvotes: 1

Views: 2213

Answers (1)

adeneo
adeneo

Reputation: 318182

I'd use perfectly valid data attributes myself :

<tr class='my_row' id='uniqueid' data-param1='param1' data-param2='param2'>

js

$('.my_row').on('mouseenter mouseleave', function() {
   var param1 = $(this).data('param1'),
       param2 = $(this).data('param2');

   .....
});

Upvotes: 1

Related Questions