【问题标题】:Uncaught TypeError: $(...).barrating is not a function - Rails / Turbolinks未捕获的类型错误:$(...).barrating 不是函数 - Rails / Turbolinks
【发布时间】:2021-12-06 07:21:52
【问题描述】:

我在我的 Rails 应用程序中使用来自 https://antennaio.github.io/jquery-bar-rating/ 的 Barrating Javascript,该应用程序使用 Turbolinks 进行页面加载。

我已将 barrating.min.js 包含在我的 javascript 中,我正在使用 //=require 将它加载到我的 application.js 中 - 一切正常。

然后,我的 assets/javascripts 区域中有一个 rating.js,用于调用在页面上创建 jquery 栏。

    document.addEventListener("turbolinks:load", function(event) {
console.log('page is fully loaded');

      //$('#user_track_rating_drums').barrating("destroy");

      $('#user_track_rating_drums').barrating({
        theme: 'bars-horizontal',
        reverse: true,
        initialRating: 1,
         onSelect: function(value, text, event) {
          if (typeof(event) !== 'undefined') {

            if (value >= 8) {
              document.getElementById('average_drums_class').className = 'green';
            }
            else if (value >= 6) { 
              document.getElementById('average_drums_class').className = 'yellow';
            }
             else if (value >= 3) { 
              document.getElementById('average_drums_class').className = 'orange';
            }
            else { 
              document.getElementById('average_drums_class').className = 'red';
            }

            // rating was selected by a user
            console.log(event.target);
          } else {
            // rating was selected programmatically
            // by calling `set` method
          }
        }
      });
})

在第一个页面加载/或者如果它手动刷新页面时一切正常,但是如果它从使用 Turbolinks 的页面导航,当我返回而不是再次创建条时,我得到一个 Uncaught TypeError: $( ...).barrating 不是函数。

我已尝试从控制台调用 barrating 函数以将其附加到页面上的其他内容,但未找到。

检查页面,barrating.min.js 仍然包含在 HEAD 中。

我尝试在再次创建它之前将其销毁,但没有成功。 我认为这是使用 turbolinks 加载页面的问题

【问题讨论】:

    标签: javascript jquery ruby-on-rails turbolinks


    【解决方案1】:

    经过反复试验,终于弄明白了。

    我从 assets/javascripts 区域中删除了调用和附加 barrating 的代码,并将其直接内嵌在所需的页面上。

    它现在在第一次和后续加载时触发而不会出错。

    不完全确定将它放在资产区域会出现什么问题,但这解决了它

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2020-01-26
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2022-11-19
    • 1970-01-01
    • 2019-06-06
    • 2019-05-24
    相关资源
    最近更新 更多