我使用Razor渲染项目列表,每个项目都有一个删除按钮。这是我的代码的简化版本:
//razor
@for (var item in Model.myList) {
<div>@item.Name <button onclick='deleteItem(@item.Id)' class='delete-button' value='Delete' /></div>
}
//javascript
<script>
function deleteItem(id) {
//ajax stuff to delete here...
alert('Item has been deleted');
}
</script>
代码效果很好。但在代码审查中,我最近被告知应该
data
属性//razor
@for (var item in Model.myList) {
<div>@item.Name <button data-id='@item.Id' class='delete-button' value='Delete' /></div>
}
//javascript
<script>
$( "div button.delete-button" ).click(function() {
var id = $(this).data('id');
//do ajax stuff here to delete
alert('Item has been deleted');
});
</script>
这也有效,并且基本上做同样的事情。但我想知道如果使用解耦合点击处理程序有任何实际好处(性能,测试,代码可读性等)?或者更多的是个人偏好?我们平均在列表中有大约100个项目。