SCRIPT5007无法获取属性'indexOf'的值

时间:2015-08-27 17:46:23

标签: javascript dom internet-explorer-8 internet-explorer-9

我需要帮助在IE9中解决此错误:“SCRIPT5007无法获取属性'indexOf'的值:对象为null或未定义”

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 个答案:

答案 0 :(得分: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 - 存在检测。)