jquery - Monkey Patch 选择了 jQuery 库 - 选择总是未定义

标签 jquery monkeypatching jquery-chosen

我正在尝试修补 Chosen jQuery 库中的两个函数,但是,无论我尝试如何引用原始函数,控制台都会返回 Chosen is undefined。

这是我的代码。

        function(){
        var _no_results = window.jQuery.fn.chosen.prototype.no_results;
        var _no_results_clear = window.jQuery.fn.chosen.prototype.no_results_clear;

        window.jQuery.fn.chosen.prototype.no_results = function (terms) {
            console.log('nr');
            var no_results_html;
            no_results_html = $('<li class="no-results">' + this.results_none_found + ' "<span></span>"</li>');
            no_results_html.find("span").first().html(terms);
            if (this.options.no_results_callback) {
                this.options.no_results_callback(no_results_html, terms);
            }
            return this.search_results.append(no_results_html);
            //return _no_results.apply(terms);
        }


        window.jQuery.fn.chosen.prototype.no_results_clear = function (terms) {
            console.log('nrc');
            var no_results_html;
            no_results_html = $('<li class="no-results">' + this.results_none_found + ' "<span></span>"</li>');
            no_results_html.find("span").first().html(terms);
            if (this.options.no_results_clear_callback) {
                this.options.no_results_clear_callback(no_results_html, terms);
            }
            return this.search_results.find(".no-results").remove();
            //return _no_results_clear.apply(terms);
        }
    }

有什么想法吗?

最佳答案

看来所选库的旧版本(例如 v0.9.14)用于公开 ChosenAbstractChosen ,但两者都没有在最新版本中曝光(截至 2019-03-25 v1.8.7)。相反,当前版本利用 .data(key, value) jQuery method存储对 Chosen 的引用chosen下的对象 key 。您可以尝试将其与初始化的选择列表和 Object.getPrototypeOf 结合使用。 JavaScript method覆盖 ChosenAbstractChosen功能。

例如,假设您页面上的某个位置有:

<select id="futureChosenSelect" ... >
  <option value="HiMom">Hi Mom!</option>
  ...
</select>

并且您已配置 <select>选择:

$('#futureChosenSelect').chosen();

您应该能够使用以下内容覆盖这些函数:

Object.getPrototypeOf( $('#futureChosenSelect').data('chosen') ).no_results = function(terms) { ... };

关于jquery - Monkey Patch 选择了 jQuery 库 - 选择总是未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14603738/

相关文章:

jquery - 获取隐藏图像的高度?

python - 在 Django 中,如何更改 User 类以使用不同的数据库表?

CSS 下拉菜单和 jquery 选择和 z-index

jquery - 如何使用 JQuery 将评论从评论部分推送到数组中?

javascript - 从 JSON 中的数组中删除列名

javascript - 使用 jQuery 创建悬停和单击功能的精益方法到 SVG 目录映射

python - "Replacing"具体函数调用

javascript - 是否可以像 C# 或 Ruby 那样提供 javascript 部分类行为?

html - 选择 : chosen-drop got cut off behind table 的响应表

javascript - 无法更改使用所选插件的 html 中的下拉选择