2016-03-07 96 views
0

我有幾個剃鬚刀局部視圖中的文本框將根據條件可用。出一個1附接有以下代碼來自動完成,但是當該局部視圖被加載然後我得到錯誤(如果文本框是不可用)自動完成渲染項目到剃刀視圖中的動態文本框?

0x800a138f - JavaScript runtime error: Unable to set property '_renderItem' of undefined or null reference

如果文本框是在剃刀視圖可用,則錯誤沒有出現。

我的jQuery代碼是

<script type="text/javascript"> 
$(function() { 
    var view = $(document).findByClass("product-view"); 
    var companysource = view.data("datasource-url"); 
    $("#txtcompany").autocomplete({ 
     minLength: 0, 
     source: function (request, resonse) { 
      $.ajax({ 
       url: companysource, 
       data: { term: $('#txtcompany').val() }, 
       dataType: "json", 
       type: "GET", 
       success: function (data) { 
        resonse(data); 
       } 
      }); 
     }, 
     focus: function (event, ui) { 
      $("#txtcompany").val(ui.item.Name); 
      return false; 
     }, 
     select: function (event, ui) { 
      $("#txtcompany").val(ui.item.Name); 
      return false; 
     }, 
     change: function (event, ui) { 
      if (ui.item == null) { 

      } else { 

      } 
     } 
    }) 
    .data("ui-autocomplete")._renderItem = function (ul, item) { 
     return $("<li>") 
      .data("ui-autocomplete-item", item) 
      .append("<div style='margin-bottom:2px; padding:1px 1px; font-size:14px;'><a>" + "<b>Company Name: </b>" + item.Name + "</a></div>") 
      .appendTo(ul); 
    }; 
}); 

回答

0

你應該先檢查是否文本框出現在DOM:

var txtcompany = $("#txtcompany"); 
    alert(txtcompany.length); 

    if (txtcompany.length === 1) { 

     txtcompany.autocomplete({ ... 

    }; 
+0

感謝@irfan。我做了那樣的.length> 1 – Hector