我得到一个未被捕获的类型错误,在尝试获取div时无法读取未定义的属性长度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我得到一个未被捕获的类型错误,在尝试获取div时无法读取未定义的属性长度相关的知识,希望对你有一定的参考价值。

我正在尝试在我的rails应用程序中包含通知,我正在按照本教程的字母https://gorails.com/episodes/in-app-navbar-notifications

一切顺利,直到我尝试使用javascript获取通知div,我应该从JSON端点附加通知。但不知何故,我无法获取div,因此整个跟随逻辑失败。

如果您需要更多代码,我很乐意与您分享我的github回购。真的很感激一些帮助:)

_navbar.html.erb

<div class="navbar-listy-right hidden-xs hidden-sm">
<% if current_user.is_a?(User) %>
  <!-- Avatar with dropdown menu -->
    <div class="btn-group dropleft" data-behavior="notifications">
      <a class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" href="#" data-behavior="notifications-link">
        <i class="far fa-bell icon-selector"></i><span data-behavior="unread-count"></span>
      </a>
      <div class="dropdown-menu" data-behavior="notification-items">

      </div>
    </div>

notifications.就是.coffee

class Notifications
constructor: ->
@notifications = $("[data-behavior='notifications']")
@setup() if @notifications.length > 0


setup: ->
console.log(@notifications)
$("[data-behavior='notifications-link']").on "click", @handleClick
$.ajax(
  url: "/notifications.json"
  dataType: "JSON"
  method: "GET"
  success: @handleSuccess
)

handleClick: (e) =>
$.ajax(
  url: "/notifications/mark_as_read"
  dataType: "JSON"
  method: "POST"
  success: ->
    $("[data-behavior='unread-count']").text(0)
)

handleSuccess: (data) =>
if data.length > 0
  items = $.map data, (notification) ->
    "<a class= 'dropdown-item' href='#{notification.url}'> # . 
{notification.actor} #{notification.action} 
{notification.notifiable.type}</a>"
    $("[data-behavior='unread-count']").text(items.length)
    $("[data-behavior = 'notification-items']").html(items)

else
    $("[data-behavior='unread-count']").text(items.length)
    $("[data-behavior='notification-items']").html("<p>No new notifications</p>")

   jQuery ->
   new Notifications

编辑

我最初的问题是,即使代码的第一步(即使用jquery获取div @notifications也失败)。但是,我知道页面加载是因为如果我在页面加载时执行警报消息。

notifications.就是.coffee

class Notifications
constructor: ->
 @notifications = $("[data-behavior='notifications']")
 @setup()



setup: ->
 console.log(@notifications)



jQuery ->
new Notifications
答案

在你的handleSuccess中,你有if-else的两个分支:

if data.length > 0
  items = ...
else
  $(...).text(items.length)

换句话说,当data.length大于零时,你引用了未定义变量lengthitems,导致你看到的错误。

有关未来的问题,请参阅有关如何创建Minimal, Complete, and Verifiable example的说明。此外,您应该在问题中包含错误消息的相关位。

以上是关于我得到一个未被捕获的类型错误,在尝试获取div时无法读取未定义的属性长度的主要内容,如果未能解决你的问题,请参考以下文章

Flutter Google 登录错误未被捕获

从 iframe 中获取 div 值

反应错误 - 未捕获的不变违规:元素类型无效

获取未捕获的类型错误:fs.readdirSync 在使用 Browserify 和 Nutritionix NodeJS 客户端库时不是一个函数

未捕获的类型错误:googleAuth.then 不是函数

未捕获的类型错误:routes.forEach 不是函数