javascript 未捕获的类型错误:无法读取未定义的属性“0”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13888685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:04:03  来源:igfitidea点击:

Uncaught TypeError: Cannot read property '0' of undefined

javascript

提问by geeta battin

Here I have div with class box-titleand I have spanwith related products and I want to change its text to 'Choose Extra To make It More Special'Why this error is coming please anyone can tell me.

在这里,我有类的 divbox-titlespan相关的产品,我想将其文本更改为 'Choose Extra To make It More Special'为什么会出现此错误,请任何人都可以告诉我。

function onloadCall()
{   
    var divs = document.getElementsByClassName('box-title');
    for(var i = 0; i < divs.length; i++)
    {
        var div = divs[i];
        if(!div) break
        var span = div.getElementsByTagName('span')[0];
        if(span[0].innerHTML == 'Related Products') 
            span[0].innerHTML='Choose Extra To make It More Special';
    }
}
window.addEventListener('load', onloadCall, false);

Actually, my HTML tag is like this:

实际上,我的 HTML 标签是这样的:

<div class="box-title"><strong><span>Related Products<span></strong></div>

采纳答案by higuaro

Change:

改变:

if(span[0].innerHTML == 'Related Products') 
    span[0].innerHTML='Choose Extra To make It More Special';

for:

为了:

if(span.innerHTML == 'Related Products') 
    span.innerHTML='Choose Extra To make It More Special';

And it should work.

它应该工作。

Also, you can change the following:

此外,您可以更改以下内容:

var span = div.getElementsByTagName('span')[0];

For:

为了:

var span = div.getElementsByTagName('span');

And leave the other code unchanged. If neither of this works, then make sure that there are any spantags in your html file.

并保持其他代码不变。如果这两种方法都span不起作用,请确保您的 html 文件中有任何标签。

回答by Charles

var span = div.getElementsByTagName('span')[0];
if(span[0].innerHTML == 'Related Products') 
    span[0].innerHTML='Choose Extra To make It More Special';

I see you grabbing the first index of the array and then trying to grab the first index of that when it isn't an array.

我看到您抓取数组的第一个索引,然后在它不是数组时尝试抓取它的第一个索引。

Try:

尝试:

var span = div.getElementsByTagName('span')[0];
if(span.innerHTML == 'Related Products') 
    span.innerHTML='Choose Extra To make It More Special';

回答by Ricardo Alvaro Lohmann

if(!div) {
    break;
}
var span = div.getElementsByTagName('span')[0];
if(span && span.innerHTML == 'Related Products') {
    span.innerHTML = 'Choose Extra To make It More Special';
}

demo

演示