【发布时间】:2014-01-13 04:05:25
【问题描述】:
我正在关注一本书来学习 JavaScript,它似乎有编码错误,因为我所关注的似乎不起作用。这是我所拥有的:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Examples of moving around in the DOM using native JavaScript methods</title>
<meta charset="UTF-8">
<!-- CSS Stylesheet -->
<link rel="stylesheet" href="css/show.css">
</head>
<body>
<!-- Let's get the parent element for the target node and add a class of "active" to it -->
<ul id="nav">
<li><a href="/" id="home">Home</a></li>
<li><a href="/about" id="about">About Us</a></li>
<li><a href="/contact" id="contact">Contact Us</a></li>
</ul>
<input type="button" onclick="targetClass()" value="Target the Class"/>
<input type="button" onclick="prevNextSibling()" value="Target Next and Previous Sibling"/>
<script src="js/js.js"></script>
</body>
</html>
JavaScript:
// This block of JavaScript obtains the parent element
// target the "about" link and apply a class to its parent list item
function targetClass()
{
document.getElementById("about").parentNode.setAttribute("class", "active");
}
// This block of code adds a Class to Previous and Next Sibling Nodes
function prevNextSibling()
{
// get "about" parent, then its previous sibling and apply a class
document.getElementById("about").parentNode.previousSibling.setAttribute("class", "previous");
// get "about" parent, then its next sibling and apply a class
document.getElementById("about").parentNode.nextSibling.setAttribute("class", "next");
}
根据本书,我应该得到的生成 HTML 的输出是:
<ul id="nav">
<li class=" previous" ><a href="/" id="home">Home</a></li>
<li class=" active" ><a href="/about" id="about">About Us</a></li>
<li class=" next" ><a href="/contact" id="contact">Contact Us</a></li>
</ul>
但是当我点击我的文本框时,什么都没有发生。
我该如何解决这个问题?
【问题讨论】:
-
删除标签之间的空格和换行符,或者重复直到找到另一个元素。
标签: javascript html dom