2009-11-09 148 views
0

我有一個表格,其中有一個「添加行」的按鈕。該按鈕可以動態地使用JQuery添加一行。它的工作方式是複製第一個...然後用遞增的數字替換所有的id =「..」。動態添加JavaScript無法在IE中找到動態添加的字段

的問題是,該行有一個YUI自動完成,看起來像下面這樣:

<td> 
    <input type="hidden" name="location_num[0]" value="508318" maxLength="25" style="width:230px" id="location_num[0]"/> 
    <input type="textbox" name="location_numDisplayDesc[0]" value="WINNIPEG" maxLength="25" style="width:230px" id="location_numDisplayDesc[0]"/> 
    <div id="Container_location_num[0]" style="display:inline;"></div> 

    <script type="text/javascript"> 

     // Initialize autocomplete 
     var location_numAC = new YAHOO.widget.AutoComplete(
      "location_numDisplayDesc[0]", 
      "Container_location_num[0]", 
      locationDataSource, 
      acConfig); 

     location_numAC.useShadow = true 
     location_numAC.useIFrame = true 
     location_numAC.dataErrorEvent.subscribe(acErrorFunction); 

     // Format results to include the reference number 
     location_numAC.formatResult = function(resultItem, query) { 
      return resultItem[0]; 
     }; 

     // Clear key before request 
     location_numAC.dataRequestEvent.subscribe(function fnCallback(e, args) { 
     YAHOO.util.Dom.get("location_num[0]").value = ""; }); 

     // Set key on item select 
     location_numAC.itemSelectEvent.subscribe(function(event, args) { 
      YAHOO.util.Dom.get("location_num[0]").value = args[2][1]; 
     }); 

     // Clear key when description is cleared 
     location_numAC.textboxBlurEvent.subscribe(function fnCallback(e, args) { 
      if (isEmpty(YAHOO.util.Dom.get("location_numDisplayDesc[0]").value)) { 
       YAHOO.util.Dom.get("location_num[0]").value = ""; 
      } // end if 
     }); 
    </script> 
</td> 

此代碼工作正常在Firefox和新創建的自動完成工作,但在IE(6 & 7)我得到一個錯誤,意味着location_num_AC沒有被成功創建。我相信這是因爲它不會讀取新創建的輸入或div。我試圖用

$("Container_location_num[0]").ready(function {...}); 

包裹,但似乎沒有工作。有沒有人有任何其他想法?

回答

2

在IE中插入到DOM中的表單字段不會像您期望的那樣添加到表單集合中。

通常情況下,你可以參考表單域之一兩種方式:

document.forms[0]["myFormName"]; 
document.forms[0][12]; 

也就是說,是由它的表單字段名稱或它的索引。但是當你在上添加一個表單域到DOM中的IE你不能只能通過它的索引來引用它的名字。如果你的代碼(或任何支持代碼)正在通過它的名字在集合中尋找一個表單域,你顯然會遇到問題。

如果你唯一的關鍵是你可以通過索引遍歷所有表單字段並找到你正在尋找的東西,但顯然這將是一個線性操作。您也可以循環查找哪些表單字段以數字形式索引,而不是按名稱索引,並自己更新表單對象。

我沒有足夠的細節知道你的項目是如何發生的(或者是否),但是它是那些IE怪癖之一,聽起來可能是因爲你動態添加字段而扮演角色。

+0

對IE的解釋/解決方法是在這裏:http://stackoverflow.com/questions/1650797/setting-name-of-dom-created-element-fails-in-ie-workaround/1651304#1651304(FYI you can在IE中指的是動態元素的名字就好了,然而魔鬼的細節) –

+0

啊,感謝那個鏈接!優秀。 –