首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >重构jquery代码

重构jquery代码
EN

Stack Overflow用户
提问于 2011-01-30 14:33:12
回答 1查看 268关注 0票数 1

如何删除data("autocomplete")...末尾的代码并将其放入函数中?

代码语言:javascript
运行
复制
    var input = $("#CountryL");

    $(input).autocomplete({
        minLength: 0,
        source: $(input).data('url')
    }).data("autocomplete")._renderItem = function (ul, item) {
        var tmp = $("<div>").setTemplate($("#"+$(input).data('template')).html());
        tmp.processTemplate(item);
        $("<li></li>").data("item.autocomplete", item)
                      .append($(tmp).html())
                      .appendTo(ul);
        return;
    }; 

我希望能够做到:

代码语言:javascript
运行
复制
function templateOverride(object){

 object.data("autocomplete")._renderItem = function (ul, item) {
        var tmp = $("<div>").setTemplate($("#"+$(input).data('template')).html());
        tmp.processTemplate(item);
        $("<li></li>").data("item.autocomplete", item)
                      .append($(tmp).html())
                      .appendTo(ul);
        return;
}


var input = $("#CountryL");

$(input).autocomplete({
        minLength: 0,
        source: $(input).data('url')
}).templateOverride(this);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-01-30 14:48:57

你就快到了。只需扩展jQuery:

代码语言:javascript
运行
复制
$.fn.extend({
  templateOverride: function () {
    return this.each(function () {
      $(this).data("autocomplete")._renderItem = function (ul, item) {
        var tmp = $("<div>").setTemplate($("#"+$(input).data('template')).html());
        tmp.processTemplate(item);
        $("<li></li>").data("item.autocomplete", item)
                      .append($(tmp).html())
                      .appendTo(ul);
      };
    });
  }
});

用法(几乎)与你所说的完全一致。

代码语言:javascript
运行
复制
$("#CountryL").autocomplete({
  minLength: 0,
  source:    $(input).data('url')
}).templateOverride();

这是一个小小的解释:

代码语言:javascript
运行
复制
// fn.extend() adds functions to the jQuery function library 
$.fn.extend({
  // it expects an object, so here we use object literal syntax (key: value)
  templateOverride: function () {
    // here "this" refers to the jQuery object you called the function on,
    // which is an array, so we iterate it with each() *and* return it
    // so jQuery function chaining does not break. 
    return this.each(function () {
      // here "this" refers to the individual HTML objects, so we must wrap
      // it in a jQuery call ($) to have access to its data()
      $(this).data("autocomplete")  // ... your code
    });
  }
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4841542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档