在多个div上使用.load AJAX

时间:2014-04-26 22:19:55

标签: jquery ajax wordpress

我在wordpress中使用.load()作为建议here的ajax分页。但是,当同一页面上有多个具有相同类和ID的循环时,它不起作用。单击后,它将加载该特定div中所有循环的div。

jquery

$('#pagination .page-numbers').live('click', function(e)  {
    e.preventDefault();
    var link = $(this).attr('href');
    $('#pagination').load(link + ' #pagination ul');
    $('#main').parent().append('<img class="opinions-loader-gif" src="http://example.com/images/AjaxLoader.gif" />');
    $('#main').animate({ opacity: 0.1 },500, function(){
        $(this).load(link + ' #main .container', function() {
            $(this).animate({ opacity: 1 },500);
            $('.opinions-loader-gif').remove();
        });
        $('#main').css('height', 'auto');
    });
    });

HTML

<!- loop1 -->
<div class="block">
    <div id="main">
        <div class="container">
            <div class="item"></div>
        <div class="item"></div>
            <div class="item"></div>
        </div>
    </div>
    <div id="pagination">
        <ul class="page-numbers">
            <li><span class="page-numbers current">1</span></li>
            <li><a class="page-numbers" href="?paged1=2&paged2=1&paged3=1">2</a></li>
            <li><a class="next page-numbers" href="?paged1=2&paged2=1&paged3=1">Next »</a></li>
        </ul>
    </div>
</div>

<!- loop2 -->
<div class="block">
    <div id="main">
        <div class="container">
            <div class="item"></div>
        <div class="item"></div>
            <div class="item"></div>
        </div>
    </div>
    <div id="pagination">
        <ul class="page-numbers">
            <li><span class="page-numbers current">1</span></li>
            <li><a class="page-numbers" href="?paged1=2&paged2=1&paged3=1">2</a></li>
            <li><a class="next page-numbers" href="?paged1=2&paged2=1&paged3=1">Next »</a></li>
        </ul>
    </div>
</div>

<!- loop3 -->
<div class="block">
    <div id="main">
        <div class="container">
            <div class="item"></div>
        <div class="item"></div>
            <div class="item"></div>
        </div>
    </div>
    <div id="pagination">
        <ul class="page-numbers">
            <li><span class="page-numbers current">1</span></li>
            <li><a class="page-numbers" href="?paged1=2&paged2=1&paged3=1">2</a></li>
            <li><a class="next page-numbers" href="?paged1=2&paged2=1&paged3=1">Next »</a></li>
        </ul>
    </div>
</div>

每次加载新内容时我都会收到http://example.com/undefined 404 (Not Found),但一切都很正常。

1 个答案:

答案 0 :(得分:0)

要将您的功能设置为使用类而不是必须唯一的ID,请执行以下操作:

<div class="pagination">
    <ul class="page-numbers">
        <li><a class="page-number" href="...">2</a></li>
        <li><a class="page-number next" href="...">Next »</a></li>
    </ul>
</div>

$('a.page-number').on('click', function(e)  {
    e.preventDefault();
    var link = $(this).attr('href');
    $(this).closest('.pagination').load(link + ' #pagination ul');
    ...