我正在尝试修补 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)用于公开 Chosen
和AbstractChosen
,但两者都没有在最新版本中曝光(截至 2019-03-25 v1.8.7)。相反,当前版本利用 .data(key, value)
jQuery method存储对 Chosen
的引用chosen
下的对象 key 。您可以尝试将其与初始化的选择列表和 Object.getPrototypeOf
结合使用。 JavaScript method覆盖 Chosen
或AbstractChosen
功能。
例如,假设您页面上的某个位置有:
<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/