在 .detach() 和 .append() 之后使用 .load() 无法按预期工作

Using .load() after .detach() and .append() not working as intended

本文关键字:工作 load detach append 之后      更新时间:2023-09-26

我在Javascript中使用.load()方法时遇到问题,它在页面加载时工作正常,但是在我分离相应的元素并再次附加它之后,该方法不再起作用。你可以在下面看到我的代码:

<script type="text/javascript">
(function () {
    var div = $('#exhibitions');
    var max = @Model.Total;
    var count = 0;
    div.find('.show-more').click(function () {
        div.find('.more-exhi').hide().load('@Url.Action("Exhibitions", "Exhibition")', { year: $(this).attr('data-year') } ).fadeIn('1500');
        div.find('.show-less').show();
        $('.more-exhi').attr('class', 'less-exhi');
        count++;
        if (count == max) {
            div.find('.show-more').hide().detach().hide();
        }
    });
    div.find('.show-less').click(function () {
        var button = div.find('button.show-more').detach();
        div.find('.more-exhi').fadeOut('1500');
        div.find('.less-exhi').fadeOut('1500');
        div.find('.show-less').hide();
        div.find('.holder').append(button);
        div.find('.show-more').attr('data-year', '@DateTime.Now.Year');
    });
})();
</script>

我使用了调试器,但就调试而言:没有错误,一切应该都正常。但是,当我单步执行加载新内容的代码部分(第 10 行)时,页面中没有添加任何内容(但是我确定 load() 方法具有有效的内容调用)。

我知道该事件有效,因为此函数中的其他方法仍然正常工作。我该怎么做才能解决此问题?

首次处理点击时,通过执行以下操作,将具有more-exhi类的任何元素上的所有类完全替换为less-exhi

$('.more-exhi').attr('class', 'less-exhi');

。然后永远不要把more-exhi放回别处。因此,在随后的点击中,此行变为无操作:

div.find('.more-exhi').hide().load('@Url.Action("Exhibitions", "Exhibition")', { year: $(this).attr('data-year') } ).fadeIn('1500');

。因为div.find('.more-exhi')找不到任何元素。