簡體   English   中英

Document.getElementsByName()在IE中返回對象,但在chrome中返回對象節點列表

[英]Document.getElementsByName() is returning object in IE but object node list in chrome

我試圖按照我的要求執行。 當我在IE瀏覽器中運行頁面時,我成功地獲得了我的要求,同樣在Chrome中無效。

for(var gridNo=0;gridNo < 30;gridNo++){

        var fldId = arry[0]+'_'+arry[1]+'_'+arry[2]+'_'+arry[3]+'_'+gridNo;

       var doc = document.getElementsByName(fldId);
       alert(doc);
       var doc1=doc;
        if(eval(doc)== null){
          alert("Oops....!");
          break;
        }

        alert("The value of the Element By Name"+doc1);
        alert("The value of the Element By Id"+document.getElementById(fldId));

var selectedDropDown = getSelectedDropDownValue(document.getElementsByName(fldId));
          alert("The Value is:"+selectedDropDown);
         if(parseInt(selectedDropDown) == 0){
             gridEmpCount = gridEmpCount + 1;
         }else if(parseInt(selectedDropDown) == 1){
             gridSpouseCount = gridSpouseCount + 1;
         }else if(parseInt(selectedDropDown) == 2){
             gridParentCount = gridParentCount + 1;
         }
     }

最后我才知道我必須使用document.getElementById(),它在IE瀏覽器中運行良好,但它在Chrome中不起作用... PLZ幫助

你的代碼有很多問題。 很難說這些IE中哪一個處理得很奇怪,但是形成IE會以奇怪的方式處理壞代碼也是如此。 解決方案是擺脫壞代碼,然后你會得到一致的行為。 以下是代碼中的錯誤列表:

  1. document.getElementsByName()返回一個列表。 它不會返回null 它永遠不會返回單個對象。 列表可能為空,沒有與元素匹配的DOM元素。

  2. if(eval(doc)== null){只是錯誤的代碼。 即使docnull ,您的代碼仍然無效。 你可以用if (!doc || !doc.length)替換那行,你可能只使用if (!doc.length)

  3. 如果只想要與名稱匹配的第一個元素,並且您確定總是至少有一個,那么執行以下操作: getSelectedDropDownValue(document.getElementsByName(fldId)[0])

  4. 您正在使用document.getElementsByName(fldId)在一個地方document.getElementById(fldId)在另一個地方。 你真的想要使用相同的長字符串作為名稱和ID嗎? 通過id獲取它將僅返回單個DOM對象。 但是按名稱提取將始終返回對象列表。

  5. 如果你打算在IE 9之前支持任何版本的IE,那么parseInt()應該總是作為第二個參數傳遞基數,否則它會根據字符串的內容猜測基數,有時會猜錯,特別是如果有的話是字符串中的前導零。

您沒有完全解釋您要完成的任務,但這里是您的代碼的清理版本:

var fldBase = arry[0] + '_' + arry[1] + '_' + arry[2] + '_' + arry[3] + '_';
for (var gridNo = 0; gridNo < 30; gridNo++) {

    var fldId =  fldBase + gridNo;
    var doc = document.getElementsByName(fldId);
    if (!doc || !doc.length) {
        alert("Oops....!");
        break;
    }

    // use doc[0] to get the first item with the name
    var selectedDropDown = parseInt(getSelectedDropDownValue(doc[0]), 10);
    alert("The Value is:" + selectedDropDown);
    if (selectedDropDown == 0) {
        gridEmpCount = gridEmpCount + 1;
    } else if (selectedDropDown == 1) {
        gridSpouseCount = gridSpouseCount + 1;
    } else if (selectedDropDown == 2) {
        gridParentCount = gridParentCount + 1;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM