views:

16

answers:

2

Here is my simple jQuery function to partially update a page

 <script type="text/javascript">
$(document).ready(function () {
    $("#prevlinkh").click(function () {
        var pagenumber = $("#prevlinkh").attr("pn");
        $("#filelist").load('/uploads/<%=FileCategoryName %>/' + pagenumber + " #filelist>*", "");
        return false;
    });

    $("#nextlinkh").click(function () {
        var pagenumber = $("#nextlinkh").attr("pn");
        $("#filelist").load('/uploads/<%=FileCategoryName %>/' + pagenumber + " #filelist>*", "");
        return false;
    });
}); 
</script>

it gets called from

<a id="prevlinkh" pn="10" href="/uploads/All/10">Previous</a>
<a id="nextlinkh" pn="12" href="/uploads/All/12">Next</a>

above links are in the div (filelist) that updated partially.

Problem is that ajax request works on first request but not on second. second request gets called as normal link click. As I understand newly loaded next and previous links some how does not get in to DOM.

How can I change this so clicking next/prev links on second time calls ajax request too. I hope my question is clear enough

A: 

The problem is that you are binding the click event when the document loads. Then, when the elements are replaced, they are reloaded with nothing bound to them. You can either rebind them, or use jQuery's live() method.

http://api.jquery.com/live/

Andy Groff
+1  A: 

One of the easiest ways is to use jQuery's live() function:

 <script type="text/javascript">
$(document).ready(function () {
    $("#prevlinkh").live('click',function () {
        var pagenumber = $("#prevlinkh").attr("pn");
        $("#filelist").load('/uploads/<%=FileCategoryName %>/' + pagenumber + " #filelist>*", "");
        return false;
    });

    $("#nextlinkh").live('click',function () {
        var pagenumber = $("#nextlinkh").attr("pn");
        $("#filelist").load('/uploads/<%=FileCategoryName %>/' + pagenumber + " #filelist>*", "");
        return false;
    });
}); 
</script>

There's also the option to use delegate(), which might be more appropriate to your needs, but I'm not entirely sure.

David Thomas