2

我在IE7中遇到了一些JS問題。我正在測試以查看某個對象是否具有分配的className(可能是來自DOM的HTMLElement對象)。現在Internet Explorer 7 - Javascript'undefined'not testing

,在Firefox測試的網頁告訴我,是的,變量是不確定的(我所有的測試下面做警報()。

在IE中,沒有一個測試通過,該變量被所分配的最後IF語句,並在最後警報()IE夾頭的「類名是空或不是對象」錯誤的基礎上,fn_note.className聲明

下面的代碼:

 var fn_note; 
     var kids = area.childNodes; 
     for (var l = 0; l < kids.length; l++){ 
      //DEBUG check if the found var exists 
      if (kids[l].className == null){ 
       //then the className var doens't exist 
       alert ('the classsname for the following var is null: --'+kids[l]+'--'); 
      } 
      if (kids[l].className == undefined){ 
       //then the className var doens't exist 
       alert ('the classsname for the following var is undefined: --'+kids[l]+'--'); 
      }      
      if (kids[l].className == ''){ 
       //then the className var doens't exist 
       alert ('the classsname for the following var is an empty string: --'+kids[l]+'--'); 
      } 
      if (typeof kids[l].className === 'undefined'){ 
       //then the className var doens't exist 
       alert ('the classsname for the following var is NEW TYPEOF TEST: --'+kids[l]+'--'); 
      }      

      if (kids[l].className == 'fn-note') { /* (/fn-note$/).test(kids[l].className) IE doesn't really like regex. por supuesto */ 
       //we have found the div we want to hide 
       fn_note = kids[l];      
      } 
     }      
     alert('the clicked on className is '+area.className+'name of the found div is '+fn_note.className); 

請讓我知道我做錯了什麼,我知道它可能有些基本的東西,但我不能看到它的ATM。

在此先感謝。

+0

剛剛在IE7上測試過:http://jsbin.com/azoya/報告一個空字符串。 – strager 2009-02-26 02:29:33

+0

也在這裏測試過它,空字符串以及 – eglasius 2009-02-26 08:36:33

回答

1

至於我可以看到你真的想知道是,如果有與childNodes集合類名「FN-筆記」一childNode的唯一的事。所以做一個更加嚴格的測試:

for (var l = 0; l < kids.length; l++){ 
    if (kids[l] 
     && kids[l].className 
     && kids[l].className.match(/fn\-note$/i)) { 
     fn_note = kids[l]; 
    } 
} 

這應該是足夠的(不要介意在正則表達式中破折號)。

6

我認爲你從屬性得到的不是一個字符串,而是一個'undefined'類型的對象。試試這個:

if (typeof(kids[l].className) == 'undefined') {