gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:03:01 26 4
gpt4 key购买 nike

我需要帮助解决 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>在这种情况下。请帮忙。

最佳答案

浏览器之间似乎存在差异。当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-detection。)

关于javascript - SCRIPT5007 无法获取属性 'indexOf' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32256158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com