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
Uncaught TypeError: Cannot read property '0' of undefined
提问by geeta battin
Here I have div with class box-title
and I have span
with 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-title
和span
相关的产品,我想将其文本更改为 '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 span
tags 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';