jquery中attr和data的区别?

2024-03-22

我正在尝试以下场景:-

  1. 我有一个页面,其中有内容(文章、博客等)。
  2. 有一些类别可以过滤它们。
  3. 因此,当我选择并分类时,包含内容的 div 会使用 jquery 进行修改。
  4. 最初显示 7 篇文章/博客等,如果内容数量超过 7,则有一个按钮可以阅读更多内容。

现在我面临一个特殊的疑问attr and data.

我在 js 文件中使用以下代码过滤内容:-

 $("[id^=filter]").click(function(){
$(".tag").children('a').removeClass("active");
$(this).addClass("active");
$('#wl-more-articles').data("current-category",$(this).data("currentCategory"));
$.get('/xxx/api/more-articles/?category='+$(this).data("currentCategory")+"&offset="+0+"&filtered="+1,
            function(result, status){
                $(".wl-cards-container").empty();
                $('.wl-cards-container').append(result.cards);
                $('#wl-more-articles').data("total-articles",result.total_content);
                if(result.next_offset >0)
                {
                     $('#wl-more-articles').show()
                }
                else
                {
                    $('#wl-more-articles').hide()
                }
            });
 });
});

在上面的代码中wl-更多文章是我获取更多文章的部分。以下是它的代码:-

    $('#wl-more-articles').click(function(){
    var el = $(this);
    $.get('/xxx/api/more-articles/?offset='+$(this).data("nextOffset")+"&content_type="+$(this).data("contentType")+"&total_articles="+$(this).data("totalArticles")+"&category="+$(this).data("currentCategory"),
            function(result, status){
      $('.wl-cards-container').append(result.cards);
      if(result.next_offset === null || result.next_offset === 'undefined'){
          el.hide();
      }else{
          el.data("nextOffset", result.next_offset);
      }
    });
  });

现在,当我选择一个特定类别(例如类别 1)时,它有 9 篇文章,因此最初会显示 7 篇文章。现在,我点击“阅读更多”按钮,一切正常,我的内容就来了。现在,当我选择另一个类别(例如类别 2),其中有 10 篇文章时,最初有 7 篇文章出现,当我单击“阅读更多”时,如果我使用attr代替data在以下部分:-

 $('#wl-more-articles').attr("data-total-articles",result.total_content);

现在,如果执行上述操作,则先前类别的数据将进入此类别(即类别 1 的类别和文章数量),但如果我使用data相反,一切都很好。


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jquery中attr和data的区别? 的相关文章

随机推荐