2015-11-17 52 views
1

enter image description here淘汰賽js和事先鍵入的內容

你好淘汰賽/預輸入專家,我得到的建議從預輸入如上js的。我提供數組格式的數據

var itemsRandom= ['Apple', 'Ball','Ape']; 

我的綁定代碼是我在這裏找到的標準綁定在stackoverflow。我綁定的文本框爲

<input type="text" data-bind="typeahead:itemsRandom,value: selectedItem"> 

數據甚至不綁定到淘汰賽JS。建議非常感謝。

ko.bindingHandlers.typeahead = { 
     init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
      var substringMatcher = function (strs) { 
       return function findMatches(q, cb) { 
        var matches, substringRegex; 

        // an array that will be populated with substring matches 
        matches = []; 

        // regex used to determine if a string contains the substring `q` 
        substrRegex = new RegExp(q, 'i'); 

        // iterate through the pool of strings and for any string that 
        // contains the substring `q`, add it to the `matches` array 
        $.each(strs, function (i, str) { 
         // console.log(str); 
         if (substrRegex.test(str)) { 
          // the typeahead jQuery plugin expects suggestions to a 
          // JavaScript object, refer to typeahead docs for more info 

          matches.push({ 
           value: str 
          }); 
         } 
        }); 

        cb(matches); 
       }; 
      }; 
      var $element = $(element); 
      var allBindings = allBindingsAccessor(); 
      var source = ko.utils.unwrapObservable(valueAccessor()); 
      var items = ko.utils.unwrapObservable(allBindings.items) || 4; 

      var valueChange = function (item) { 
       allBindings.value(item); 
       return item; 
      }; 
      debugger; 
      $element.attr("autocomplete", "off") 
        .typeahead({ 
          hint: true, 
          highlight: true, 
          minLength: 0, 
          selectable: 'Typeahead-selectable' 
        }, { 
          valueKey: 'value', 
          source: substringMatcher(source), 
          items: items, 
          updater: valueChange 
        }); 
     } 
    }; 

回答

0

要以KO綁定自動完成,我在上面取出更新代碼和用法如下

var updateValues = function (val) { 
       allBindings.value(val); 
      }; 
      // debugger; 
      $element.attr("autocomplete", "off") 
        .typeahead({ 
          hint: true, 
          highlight: true, 
          minLength: 0, 

        }, { 
         source: substringMatcher(source), 
         items: allBindings, 
         displayKey: 'value', 
         limit:100 

        }).on('typeahead:selected', function (el, item) { 
         updateValues(item.value); 
        }).on('typeahead:autocompleted', function (el, item) { 
         updateValues(item.value); 
        }); 
     } 
    }; 
1

如果您使用的是最新版本的typehead即0.11,然後代替

valueKey: 'value', 

使用

displayKey: 'value',