2015-08-27 27 views
0

帮助我解决这个错误在IE9:“SCRIPT5007无法获取财产‘的indexOf’的值:对象为null或undefined”SCRIPT5007无法获取财产的价值“的indexOf”

findParent = function (father, str, prop) { 
 
    /** 
 
    * Go up the DOM tree and find the parent element with the specified class or prop name. 
 
    * @param {Object} father - (HTMLElement) 
 
    * @param {String} str - the class of the father 
 
    * @param {string} prop - some other property such as name or id 
 
    * @example var parentEl = findParent(container, 'genericForm', 'name'); 
 
    */ 
 
    'use strict'; 
 

 
    if (prop === undefined || typeof prop !== 'string') { 
 
     prop = 'className'; 
 
    } 
 

 
    while ((father !== undefined || typeof father !== 'string' || father !== null) && (father = father.parentElement) && !(father[prop].indexOf(str) >= 0)); 
 

 
    return father; 
 
}; 
 

 
var container = document.getElementById('description'); 
 
var parentEl = findParent(container, 'gForm', 'name'); 
 
alert(parentEl);
<form action="/gform.html" class="campaign-forms" method="post" name="gForm"> 
 

 
    <fieldset class="fieldset" title="Type your question..."> 
 
     <textarea name="description" id="description" placeholder="Type your question..." data-ana-label="Type your question..."></textarea> 
 
     <small class="error"><i class="close">×</i> This is a required field</small> 
 
    </fieldset> 
 

 
</form>

我希望它在这种情况下返回<form>。请帮忙。

+1

看着IE中的调试器,它说,'father'是'fieldset'元素和'prop'是'name'。但是,代码中的字段集没有名称,因此是错误的。 – Teemu

+0

是的,但它不应该继续下去了DOM,直到找到父与指定的道具?这就是'while'的意思,对吧?这就是它是如何工作的其他地方,至少,Chrome浏览器,火狐,Safari ... – colecmc

+1

不,'爸爸[“名”]''是undefined',它不是说方法。 – Teemu

回答

1

它的出现,是有浏览器之间的差异。当没有明确定义father[prop],IE返回undefined,其他浏览器似乎返回一个空字符串。

为了解决这个问题,你可以检测undefined,并用一个空字符串,像这样的东西替代它:

findParent = function (father, str, prop) { 
    'use strict'; 

    if (prop === undefined || typeof prop !== 'string') { 
     prop = 'className'; 
    } 

    while (father && (father = father.parentElement) && !((father[prop] || '').indexOf(str) >= 0)); 
                  ^^^^^^^^^^^^^^^^^^^^ 
    return father; 
}; 

A live demo at jsFiddle

(我刚刚简化条件的位,你可以,如果你想使用原来father -exists检测。)

+1

太棒了!再次感谢你。 – colecmc

相关问题