无法读取属性“父节点”
Cannot read property 'parentNode'
我开始学习javascript,我一辈子都想不通,为什么这个"无法读取属性'parentNode'"被扔到控制台中;为什么for循环在第三个链接之后调用an。
我正在学习有关javascript翻转的课程,翻转有效,但是为什么会抛出错误?
<style type="text/css" media="screen">
#caption, #content {
width: 30%;
float: left;
padding: 10%;
line-height: 1.675em;
}
</style>
<script type="text/javascript" charset="utf-8">
window.onload = initRollover;
function initRollover() {
for (var i = 0; i < document.links.length; i++) {
console.log(i);
if(document.images[i].parentNode.tagName == "A") {
setupRollover(document.images[i]);
}
document.links[i].setAttribute('class', 'test');
}
}
function setupRollover(thisImage){
thisImage.outImage = new Image();
thisImage.outImage.src = thisImage.src;
thisImage.onmouseout = function() {
this.src = this.outImage.src;
}
thisImage.overImage = new Image();
thisImage.overImage.src = "images/" + "silver" + ".jpg";
thisImage.onmouseover = function(){
this.src = this.overImage.src;
}
}
</script>
<div id="content" style="background: lightgreen;">
<img src="images/silver.jpg" width="240" alt="Silver" id="photoA">
<br><br>
<a href="boom.html">
<img src="images/gold.jpg" width="240" alt="Gold" id="photoB">
</a>
</div>
<div id="caption">
<a href="foo.html">Lorem ipsum dolor sit amet,</a> consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. <a href="bar.html">Duis aute irure dolor </a>in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in <a href="car.html">culpa qui officia deserunt</a> mollit anim id est laborum.
</div>
<div style="clear:both"></div>
谢谢
我不完全确定您要实现的目标。但我看到的问题就在这里
function initRollover() {
for (var i = 0; i < document.links.length; i++) {
console.log(i);
if(document.images[i].parentNode.tagName == "A") {
setupRollover(document.images[i]);
}
document.links[i].setAttribute('class', 'test');
}
}
在您的 html 代码中,有 3 个带有标签的链接,但只有 2 个带有标签的图像。所以当i = 2时,没有document.images[2]。因此,父节点为空。这会导致您的错误。
希望有帮助。
相关文章:
- 在自定义截面树中获取父节点
- 使用javascript从节点属性获取数组值
- 如何避免在取消选中子节点时取消选中父节点
- 如果未选中子节点,则未选中父节点
- JavaScript 文本节点属性
- 仅使用某些子节点访问xml中父节点的子节点
- 如何以编程方式在 jsTree 中选择一个节点并打开所有父节点
- hasOwnProperty 在对照父对象属性进行检查时返回 true
- 使用Javascript设置带有子节点的父节点的类's文本等于.
- 如何确定父节点是否有子节点
- Javascript在没有jQuery的情况下获取X父节点
- 如何从wijmo-flex网格的树视图中的节点转到父节点
- 无法读取属性“父节点”
- mcDropDown 插件:如何显示父节点属性
- 正在获取父节点的属性
- 递归函数未捕获父DOM节点属性
- element.appendChild(node)是否将父节点的属性应用到子节点
- 在Javascript中解析XML时从父节点获取属性
- 如何更改子节点事件上的父节点样式属性
- 无法解析父节点自定义属性