【问题标题】:Internet Explorer 7 - Javascript 'undefined' not testingInternet Explorer 7 - Javascript“未定义”未测试
【发布时间】:2010-10-09 23:38:37
【问题描述】:

我在 IE7 中遇到了一些 JS 问题。我正在测试是否为某个对象分配了一个类名(它可能是来自 DOM 的 HTMLElement 对象)。

现在,在 Firefox 中测试页面告诉我,是的,变量未定义(我下面的所有测试都执行 Alert()。

在 IE 中,没有任何测试通过,变量在最后一个 IF 语句中分配,并且在最后一个 Alert() 期间,IE 根据fn_note.className 语句抛出“className is null or not an object”错误.

代码如下:

        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 上看不到它。

提前致谢。

【问题讨论】:

  • 刚刚在 IE7 上测试过:jsbin.com/azoya 报告一个空字符串。
  • 也在这里测试过,空字符串也是如此

标签: javascript internet-explorer firefox internet-explorer-7 cross-browser


【解决方案1】:

我认为你从属性中得到的不是字符串,而是“未定义”类型的对象。试试这个:

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

【讨论】:

  • 嗯,不完全是。该代码对根本不需要的类型字符串进行了额外的类型检查,实际上可能会导致问题。有一个字面量字符串类型和一个字符串对象,它们可能不会被评估为相同的类型。
【解决方案2】:

据我所知,您真正想知道的唯一一件事是在 childNodes 集合中是否有一个 className 为“fn-note”的 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];
    }
}

这应该足够了(请注意转义正则表达式中的破折号)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    相关资源
    最近更新 更多