如何在jQuery的ajax自动完成中编辑此代码

时间:2011-09-01 09:08:08

标签: javascript jquery ajax jquery-autocomplete

您正在使用ajax autocomplete for jquery插件

http://www.devbridge.com/projects/autocomplete/jquery/

有一个代码

  function Autocomplete(el, options) {
    this.el = $(el);
    this.id = options.id;
    this.el.attr('autocomplete', 'off');
    this.suggestions = [];
    this.data = [];
    this.badQueries = [];
    this.selectedIndex = -1;
    this.currentValue = this.el.val();
    this.intervalId = 0;
    this.cachedResponse = [];
    this.onChangeInterval = null;
    this.ignoreValueChange = false;
    this.serviceUrl = options.serviceUrl;
    this.isLocal = false;

    //this.options.fnFormatResult = fnFormatResult();

    this.options = {
      autoSubmit: false,
      minChars: 1,
      maxHeight: 300,
      deferRequestBy: 0,
      width: 0,
      highlight: true,
      params: {}, 
      fnFormatResult: fnFormatResult,      
      delimiter: null,
      zIndex: 9999
    };
    this.initialize();
    this.setOptions(options);
  }

在那里

this.options = {
  autoSubmit: false,
  minChars: 1,
  maxHeight: 300,
  deferRequestBy: 0,
  width: 0,
  highlight: true,
  params: {}, 
  fnFormatResult: fnFormatResult,      
  delimiter: null,
  zIndex: 9999
};

它定义了一个格式化结果的函数

fnFormatResult: fnFormatResult,   

我想使用fnFormatResult之外的函数,例如fnFormatResult2

我想根据参数传递给插件

更改调用函数

我需要这样做

if(param == 1){
 fnFormatResult: fnFormatResult,   
}
else if(param == 1){
 fnFormatResult: fnFormatResult2,   
}

我该怎么办?请帮助......................

2 个答案:

答案 0 :(得分:2)

嗯,我想你可以做到:

this.options = {
  autoSubmit: false,
  minChars: 1,
  maxHeight: 300,
  deferRequestBy: 0,
  width: 0,
  highlight: true,
  params: {}, 
  fnFormatResult: function(value, data, currentValue) {
    if(param==1) {
      return fnFormatResult.call(this, value, data, currentValue);
    } else if (param==2) {
      return fnFormatResult2.call(this, value, data, currentValue);
    }
  },      
  delimiter: null,
  zIndex: 9999
};

答案 1 :(得分:1)

我认为您可以对功能进行一些更改:

function fnFormatResult(value, data, currentValue) {
    var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
    return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
  }

你可以在这个功能中实现两个定义。