什么';将相同的ajax函数添加到注释列表中的最佳方法是什么?

什么';将相同的ajax函数添加到注释列表中的最佳方法是什么?,ajax,jquery,Ajax,Jquery,源代码如下所示: <div> <h4>comment content</h4> <a id="delcmt_{{ comment.id }}">delete this comment</a> </div> ...... <div> <h4>comment content</h4> <a id="delcmt_{{ comment.id }}">d

源代码如下所示:

<div>
    <h4>comment content</h4>
    <a id="delcmt_{{ comment.id }}">delete this comment</a>
</div>
......
<div>
    <h4>comment content</h4>
    <a id="delcmt_{{ comment.id }}">delete this comment</a>
</div>

评论内容
删除此评论
......
评论内容
删除此评论
我想向每个“删除此评论”链接添加ajax功能:


$(函数(){
$('a#delcmt_id').bind('click',function()){
$.get($SCRIPT\u ROOT+/del\u comment){
},函数(数据){
$(“#结果”).value(data.result);
});
返回false;
});
});

我能说的是,使用循环为每个注释复制上层ajax函数,这一定非常难看。有什么好主意吗?

尝试添加一个类,并使用jquery添加事件处理程序选择它。您必须使用“on”事件,因为您希望将行为附加到的元素可能是动态的,并在文档准备就绪后加载

   @*Render all this with razor, or angular or knockout*@
    <div>
        <h4>comment content</h4>
        <span style="cursor: pointer;" id="1" data-rowid="1" class="delete-me-class">delete this comment</span>
    </div>
    <div>
        <h4>comment content</h4>
        <span style="cursor: pointer;" id="2" data-rowid="2" class="delete-me-class">delete this comment</span>
    </div>

    <script>
        $(function () {
            $('body').on('click', '.delete-me-class', function () {//http://api.jquery.com/on/  on is the latest 'live' binding for elements that may not exists when DOM is ready.
                var rowId = $(this).data('rowid');
                //TODO Use rowId for your delete ajax, or your element Id if you wish.
                alert('You clicked on the delete link with the row ID of ' + rowId);
            });
        });
    </script>
@*使用razor、angular或knockout渲染所有这些*@
评论内容
删除此评论
评论内容
删除此评论
$(函数(){
$('body')。在('click','delete me class',function()上{//http://api.jquery.com/on/  on是DOM就绪时可能不存在的元素的最新“活动”绑定。
var rowId=$(this.data('rowId');
//TODO在delete ajax中使用rowId,如果愿意,也可以使用元素Id。
警报('您单击了行ID为'+rowId'的删除链接);
});
});

   @*Render all this with razor, or angular or knockout*@
    <div>
        <h4>comment content</h4>
        <span style="cursor: pointer;" id="1" data-rowid="1" class="delete-me-class">delete this comment</span>
    </div>
    <div>
        <h4>comment content</h4>
        <span style="cursor: pointer;" id="2" data-rowid="2" class="delete-me-class">delete this comment</span>
    </div>

    <script>
        $(function () {
            $('body').on('click', '.delete-me-class', function () {//http://api.jquery.com/on/  on is the latest 'live' binding for elements that may not exists when DOM is ready.
                var rowId = $(this).data('rowid');
                //TODO Use rowId for your delete ajax, or your element Id if you wish.
                alert('You clicked on the delete link with the row ID of ' + rowId);
            });
        });
    </script>