未捕获的类型错误:当我的目标是追加元素时,$(...).offset() 未定义

我的控制台出现错误:

未捕获的类型错误:$(...).offset() 未定义

<div>在此之前,我使用 id创建了父级contentMessage,我从数据库中获取了所有数据,并进行了 jQuery 操作以在成功响应中循环该数据,我循环元素 a </div class"alert">,然后将其附加到我的父级中<div id="contentMessage">。当我想自动滚动到附加的最新警报时,出现错误。

//my append element into `<div id=contentMessage>`

$.ajax({

  url: "<?= $apiEndpoint ?>/message/",

  type: "GET",

  data: {

    outlet_from: outlet_from,

    outlet_to: outlet_to,

    from: id_from,

    to: id_to

  },

  dataType: "JSON",

  success: function(res) {

    let a = 0

    let resCount = res.length

    window.count = resCount -= 1


    if (res.length == 0) {

      var append = $('<div/>', {

        "class": "parent_message p-2",

      }).append(

        $('<div/>', {

          'class': 'text-center',

          text: 'Tidak Ada Pesan'

        })

      )


      $("#contentMessage").append(append)

    }

    $.each(res, function(key, val) {

      var d = new Date(res[a].created_at)

      if (d.getMinutes() < 10) {

        var times = d.getHours() + ":" + "0" + d.getMinutes()

      } else {

        var times = d.getHours() + ":" + d.getMinutes()

      }


      if (res[a].from === <?= $user_id ?>) {

        if (a == window.count) {

          window.message = $('<div/>', {

            "class": "alert alert-primary alert-dismissible alertFrom ",

            "id": "resMessage",

            text: res[a].message

          }).append($('<small/>', {

            text: times

          }))

        } else {

          window.message = $('<div/>', {

            "class": "alert alert-primary alert-dismissible alertFrom",

            text: res[a].message

          }).append($('<small/>', {

            text: times

          }))

        }



这是我的滚动代码:


window.setTimeout(function() {

  $('.contentMessage').animate({

    scrollTop: $("#resMessage").offset().top

  }, 3000);

}, 2000);


撒科打诨
浏览 113回答 1
1回答

斯蒂芬大帝

只需将“scrollfunction”放置在创建 id resMessage 的元素的代码下方即可。否则(在您的示例中,如果 ajax 响应和元素创建花费的时间超过 2000 毫秒,则该元素将不存在,您将看到您描述的错误)success:function(res){&nbsp; ...&nbsp; window.setTimeout(function() {&nbsp; &nbsp; $('.contentMessage').animate({&nbsp; &nbsp; &nbsp; scrollTop: $("#resMessage").offset().top&nbsp; &nbsp; }, 3000);&nbsp; }, 2000);}可能不再需要超时了;)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript