加载ajax请求后,jQuery PreventDefault()无法正常工作

时间:2018-06-16 18:17:58

标签: javascript jquery ajax

我正在使用ajax请求点击下一周和上一周。首先看一下图片。enter image description here

好的,下周和Prev周都有相同的班级whole-week,以下是此表的基本html

<table class="sevent-weekly-view">
<thead>
    <tr>
        <td>
            <a class="whole-week" href="" data-week="24" data-year="2018">Prev Week</a>
        </td>
        ...
        <td>Tue<br><span class="weekly-date">19</span></td>
        ...
        <td>
            <a href="" class="whole-week" data-week="26" data-year="2018">Next Week</a>
        </td>
    </tr>
</thead>
</table>

我的ajax请求正在回复如下

<thead>
    <tr>
        <td>
            <a class="whole-week" href="" data-week="24" data-year="2018">Prev Week</a>
        </td>
        ...
        <td>Tue<br><span class="weekly-date">25</span></td>
        ...
        <td>
            <a href="" class="whole-week" data-week="26" data-year="2018">Next Week</a>
        </td>
    </tr>
</thead>

我正在用ajax请求替换表内容。第一次它工作正常。但是在第一次响应后防止默认不起作用。

以下是JS代码

 var _getweekevents = function(week, year){
 var table = jQuery('.sevent-weekly-view');
    jQuery.ajax({
        type: 'post',
        url: seventdata.ajaxurl,
        data:{
            action: 'sevent_weekly_posts',
            week : week,
            year: year,
        },
        beforeSend: function(){},
        success: function(request){
            table.html(request.table);
        },
    });
}

var weekly = jQuery(document).find('.whole-week');

weekly.each(function(index){
    jQuery(this).on('click', function(e){
        e.preventDefault();
        var week = jQuery(this).data('week');
        var year = jQuery(this).data('year');
        _getweekevents(week, year);
    });
});
  

我的Ajax请求和所有其他请求都正常工作,没有产生任何错误。我也试过jQuery('.whole-week')

1 个答案:

答案 0 :(得分:0)

当你删除一个元素然后替换它(通过javascript)时,它会丢失在页面加载时添加到它的任何事件绑定。所以你需要在ajax成功后绑定click事件。您也不需要循环.whole-week。     bindClick()

var _getweekevents = function(week, year){
var table = jQuery('.sevent-weekly-view');
    jQuery.ajax({
        type: 'post',
        url: seventdata.ajaxurl,
        data:{
            action: 'sevent_weekly_posts',
            week : week,
            year: year,
        },
        beforeSend: function(){},
        success: function(request){
            table.html(request.table);
        },
    });
}

function bindClick() {
    $('.sevent-weekly-view').on('click', '.whole-week', function(e){
        e.preventDefault();
        var week = jQuery(this).data('week');
        var year = jQuery(this).data('year');
        _getweekevents(week, year);
    });   
}