我渲染一个包含表格的 View 。表格的每一行都是一个可以编辑的对象。所以,这个表的最后一列有一堆“编辑”按钮。单击其中一个“编辑”按钮时,JavaScript 函数必须获取当前行表示的对象的 ID。最终,我希望得到一个干净的 HTML:没有“onclick”、“onmouseover”属性,也没有自定义的虚构属性。下面我有 2 个我不满意的例子。有什么好的想法吗?
示例 1:
View .aspx
<td>
<input type="button" value="EDIT" onclick="JSFunction(<%: ObjectId %>)" />
</td>
JavaScript
function JSFunction(id)
{
//some code that does whatever with id
}
示例 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 that does whatever with id
});
附言如果您能想出更好的问题标题,也请分享:)
最佳答案
我过去处理这个问题的一种方法是使用 html5 数据属性。 jQuery 1.4.3 的版本选择了哪个及以上。
<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>
然后在您的 jquery 中您可以执行以下操作:
$("input[type=button]").click(function(){
var rowInfo = $(this).parents("tr.row").data("rowInfo");
//Do something with rowInfo.Id;
});
通过使用数据属性,您可以获得一个丰富的 json 对象,它可以包含比属性更多的信息。此外,您只需声明一个数据属性即可保存所有相关信息。
在 jsfiddle 上工作的示例.
关于javascript - 将参数从服务器对象传递到 JavaScript 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5098311/