推特的 typeahead.js依赖于 jQuery 1.9 ( documentation ),但是 Zurb Foundation 4将尝试在现代浏览器中加载 Zepto.js。如果没有加载 jQuery 1.9,typeahead.js 将抛出错误($.deferred 未定义
),显示需要进行哪些更改才能使这两个库协同工作?
最佳答案
为此,我使用默认的 Zepto 1.0 和 typeahead.js 0.9.3(这是我撰写本文时的最新发布版本)
抛出的第一个错误实际上不是您将遇到的最后一个问题,但这是我为使其正常工作所做的工作(连同我添加的 CSS 使其看起来像是属于 Foundation 4)。首先添加我包含的缺少的延迟支持 simply-deferred .一旦加载了 Zepto.js 和 simply-deferred,您将需要添加这一行以使 simply-deferred 的行为像 jQuery:
Deferred.installInto(Zepto);
然后您需要对 typahead.js 进行 2 处更改,第一个(在 line 328 处),获取远程数据的原始函数使用 jQuery 模式 .$(ajax(url, {options})
看起来像这样:
var that = this, jqXhr = pendingRequests[url];
if (!jqXhr) {
incrementPendingRequests();
jqXhr = pendingRequests[url] = $.ajax(url, this.ajaxSettings).always(always);
}
为了使 Zepto 工作(谁的 $.ajax()
函数只接受一个参数并将 URL 作为 {options}
对象的一部分)更改代码看起来像这样:
var that = this, jqXhr = pendingRequests[url], ajaxOptions = {'url': url};
if (!jqXhr) {
incrementPendingRequests();
$.extend(ajaxOptions, this.ajaxSettings);
jqXhr = pendingRequests[url] = $.ajax(ajaxOptions).always(always);
}
这种方法适用于 Zepto 和 jQuery。然后在 typaeahead.js 的底部有两个对 jQuery 的硬编码引用,如下所示:
jQuery.fn.typeahead = function(method) {
if (methods[method]) {
return methods[method].apply(this, [].slice.call(arguments, 1));
} else {
return methods.initialize.apply(this, arguments);
}
};
})();
})(window.jQuery);
这很容易更改为更兼容:
$.extend($.fn, {
typeahead: function(method) {
if (methods[method]) {
return methods[method].apply(this, [].slice.call(arguments, 1));
} else {
return methods.initialize.apply(this, arguments);
}
}
});
})();
})(window.$);
最后,因为 typeahead.js 在初始化时向 DOM 添加了一些标记,这与 foundation.css 的一些困惑,以抵消它(并设置它创建的 HTML 的样式,使其看起来更适合基金会)我添加了这个 CSS:
span.tt-dropdown-menu {
background-color: #fff;
border: 1px solid #ccc;
margin-top: -15px;
width: 100%;
}
div.tt-suggestion.tt-is-under-cursor {
background-color: #ccc;
}
div.tt-suggestion > p {
margin: 0;
line-height: 35px;
}
span.twitter-typeahead {
width: 100%;
}
我希望这可以节省其他人我整理的时间:)
关于javascript - 我如何将 typeahead.js 与 Zepto.js 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19415663/