jquery - Best way to pass parameters from server objects to JavaScript -
i render view table in it. each row of table object edited. so, last column of table has bunch of "edit" buttons. when 1 of these edit buttons clicked, javascript function must pick id of object represented current row. ultimately, end clean html: no "onclick", "onmouseover" attributes , no custom made-up attributes. below have 2 examples i'm not thrilled with. ideas?
example 1:
view.aspx
<td> <input type="button" value="edit" onclick="jsfunction(<%: objectid %>)" /> </td>
javascript
function jsfunction(id) { //some code whatever id }
example 2:
view.aspx
<td> <input type="button" value="edit" customattribute="<%: objectid %>" /> </td>
javascript
$('input[type=button]').click(function() { var id = this.attr('customattribute'); //some code whatever id });
p.s. if come better question title, please share :)
one way handled in past use html5 data-attribute. picked versions of jquery 1.4.3 , above.
<table> <tr class="row" data-rowinfo='{"id": "1", "name": "jon"}'> <td> row id 1 </td> <td> <input type="button" value="edit"/> </td> </tr> <tr class="row" data-rowinfo='{"id": "2", "name": "mark"}'> <td> row id 2 </td> <td> <input type="button" value="edit"/> </td> </tr> <tfoot> <tr> <td></td> </tr> </tfoot> </table>
then in jquery can following:
$("input[type=button]").click(function(){ var rowinfo = $(this).parents("tr.row").data("rowinfo"); //do rowinfo.id; });
by using data attribute can have rich json object contain more information attribute. plus have declare 1 data-attribute hold relevant information.
example of working on jsfiddle.
Comments
Post a Comment