开发者

dynamic jquery listener

How can i create a 开发者_如何学Pythondynamic listener using jquery to run different ajax tasks?

For example, stackoverflow have a delete link for each comment without onlick in it, so i'm guessing that they created a class listener, but how does it know which id to use in the ajax url?


Your HTML could contain something like:

<span class="delete-link" data-id="15">Delete comment 15</span>

Then, with jQuery, you could add callbacks on that class:

$('.delete-link').click(function() {
    var comment_id = $(this).data('id');
    /* send ajax request for that comment ID */
});


I believe this is done by the id property on the tr ancestor of the comment.

The HTML looks something like this:

<tr id="comment-7507745" class="comment">
    <td class="comment-actions">
        <table>
        <tbody>
        <tr>
            <td class="comment-score">
                <span>&nbsp;</span>
            </td>
            <td>
                <a class="comment-up comment-up-off" title="this is a great comment">upvote</a>
            </td>
        </tr>
            <!-- and a whole bunch more -->
    </td>
</tr>

So the code might be implemented with code a bit like this:

$(document).delegate('a.comment-up', 'click', function(event) {
    var commentId = $(this).closest('tr.comment').attr('id').substr(8);

    // do something with the comment id
});

So the data is stored as an attribute, and DOM traversal is used to find the relevant element where the data is stored.


with the bind method

$('a', '#container').bind('click',function(e){
    /* stuff */
});

(and unbind, for removing)

Or if you are asynchronously appending new links you can use the live function

$('a', '#container').live('click',function(e){
    /* stuff */
});

(opposite of live, is die( event ) )

Clicking on a link, child of #container will call the anonymous function within the arguments of bind/live, You can then check which link was clicked by checking for its index, or class, or anything - and run different code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜