【问题标题】:bootstrap-star-rating plugin causes an error: Uncaught TypeError: $(...).rating is not a functionbootstrap-star-rating 插件导致错误:Uncaught TypeError: $(...).rating is not a function
【发布时间】:2017-09-18 13:55:46
【问题描述】:

我已经通过 bower 安装了 plugin 并将其包含在 bower.json 文件中:bower install bootstrap-star-rating --save。在视图中(这是一个 Rails 项目)我有这段代码:

<%= form.text_field :rating,
                            id: :review_rating,
                            class: 'form-item large-6 cell',
                            placeholder: 'Rating*',
                            required: true %>

我的 js 由 gulp 编译成 public/layout 并存在于 application.js 中。在config/application.rb我有这段代码:

config.assets.paths << Rails.root.join('public', 'layout')

因此,layout 目录存在于资产管道中。 我用来初始化星级的代码是:

$('#review_rating').rating({
        min: 1,
        max: 5,
        step: 1,
        size: 'sm',
        theme: 'krajee-uni'
    });

如果插件作为依赖项存在于 bower.json 中,为什么会出现错误:Uncaught TypeError: $(...).rating is not a function

【问题讨论】:

  • 检查您的实际标记。 JQuery 必须出现在任何其他 Javascript 插件之上。即,您必须首先在标记中引用 JQuery.min.js 脚本。

标签: javascript jquery ruby-on-rails plugins bower


【解决方案1】:

触发错误的函数位于 bootstrap star-rating github 存储库的498

$.fn.rating = function (option) {
    var args = Array.apply(null, arguments), retvals = [];
    args.shift();
    this.each(function () {
        var self = $(this), data = self.data('rating'), options = typeof option === 'object' && option,
            theme = options.theme || self.data('theme'), lang = options.language || self.data('language') || 'en',
            thm = {}, loc = {}, opts;
        if (!data) {
            if (theme) {
                thm = $.fn.ratingThemes[theme] || {};
            }
            if (lang !== 'en' && !$h.isEmpty($.fn.ratingLocales[lang])) {
                loc = $.fn.ratingLocales[lang];
            }
            opts = $.extend(true, {}, $.fn.rating.defaults, thm, $.fn.ratingLocales.en, loc, options, self.data());
            data = new Rating(this, opts);
            self.data('rating', data);
        }

        if (typeof option === 'string') {
            retvals.push(data[option].apply(data, args));
        }
    });
    switch (retvals.length) {
        case 0:
            return this;
        case 1:
            return retvals[0] === undefined ? this : retvals[0];
        default:
            return retvals;
    }
};

该函数未包含在您的资产管道中。 star-rating.js 文件不包含在您的 application.js

要对此进行测试,只需运行您的服务器 rails s,打开您的页面,然后使用 f12 打开 chrome 开发人员工具栏并在源部分中搜索该文件。

使用 ruby​​ on rails 我不使用 bower 来安装插件,也许将所有相关的 js、css 文件和图像包含在您的 application.js.scss 和正确的图像文件夹中就足够了.

https://github.com/kartik-v/bootstrap-star-rating

如果您有任何其他问题,请告诉我。

【讨论】:

  • 我决定将正确的 js 和 css 文件放到供应商目录中,现在一切正常。谢谢。
  • @AlexZakruzhetskyi 太棒了!
猜你喜欢
  • 2015-12-01
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 2018-07-17
  • 2023-02-17
相关资源
最近更新 更多