为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

撒科打诨 2023-08-18 16:25:02
我的控制台出现错误:未捕获的类型错误:$(...).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);
查看完整描述

1 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

只需将“scrollfunction”放置在创建 id resMessage 的元素的代码下方即可。否则(在您的示例中,如果 ajax 响应和元素创建花费的时间超过 2000 毫秒,则该元素将不存在,您将看到您描述的错误)


success:function(res){


  ...


  window.setTimeout(function() {

    $('.contentMessage').animate({

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

    }, 3000);

  }, 2000);

}

可能不再需要超时了;)


查看完整回答
反对 回复 2023-08-18
  • 1 回答
  • 0 关注
  • 61 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信