如何修复“未捕获的TypeError:无法读取未定义的属性'scrollHeight'”错误

时间:2020-04-15 18:28:43

标签: javascript ruby-on-rails

Rails应用程序中ActionCable设置的大多数代码都在一个文件中,该文件似乎仅在我访问以该资源命名的页面时才加载。在这种情况下,scroll_bottom()在消息#index上运行时运行,但在其他任何地方时都会在控制台中引发错误。

我可以说这与$(document).on 'turbolinks:load', ->有关。当我不在scroll_bottom()页面上时,如何排除#index

messages.coffee

App.messages = App.cable.subscriptions.create "MessagesChannel",
 connected: ->
  console.log 'Connected'

 disconnected: ->
  console.log 'Disconnected'

 received: (data) ->
  alert data["mmmm"]

 peak: (message, conversation_id) ->
  @perform 'speak', message: message, conversation_id: conversation_id

$(document).on 'turbolinks:load', ->
 submit_message()
 scroll_bottom()

submit_message = () ->
 $('#response').on 'keydown', (event) ->
  if event.keyCode is 13
   message = event.target.value
   conversation_id = $("#messages").data("conversation-id")
   App.messages.speak(message, conversation_id)
   event.target.value = ""
   event.preventDefault()

scroll_bottom = () ->
 $('#messages').scrollTop($('#messages')[0].scrollHeight)

1 个答案:

答案 0 :(得分:1)

scroll_bottom = () ->
 $('#messages').scrollTop($('#messages')[0].scrollHeight)

将此功能更改为:

scroll_bottom = () => {
 const el = $('#messages').scrollTop($('#messages')[0]
 if (el) {
  return el.scrollHeight;
 }
}

那样,如果未定义el,则不会抛出错误