JavaScript中的ParentNode和previousSibling

时间:2013-12-25 03:58:22

标签: javascript html dom

我正在阅读一本书来学习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>

但是当我点击我的文本框时,没有任何事情发生。

如何解决此问题?

2 个答案:

答案 0 :(得分:8)

某些浏览器在DOM元素之间插入空格
阅读以下链接中的备注部分 https://developer.mozilla.org/en-US/docs/Web/API/Node.nextSibling

解决方案是使用prevElementSibling和nextElementSibling。这将选择具有相同类型的下一个兄弟

此作品http://jsfiddle.net/E2k6t/1/

function targetClass()
{
   document.getElementById("about").parentNode.setAttribute("class", "active");
}
function prevNextSibling()
{
  document.getElementById("about").parentNode.previousElementSibling.setAttribute("class", "previous");
  document.getElementById("about").parentNode.nextElementSibling.setAttribute("class", "next");
}

注意

在您进行实际开发时,不建议您在HTML代码中使用内联javascript(onclick =“targetClass()”) - 讨论herehere。使用Event Listeners

答案 1 :(得分:0)

如果使用检查器检查DOM,您将看到li元素之间存在空文本节点。要解决这个问题:

// get "about" parent, then its previous sibling and apply a class
document.getElementById("about").parentNode.previousSibling.previousSibling.setAttribute("class", "previous");

// get "about" parent, then its next sibling and apply a class
document.getElementById("about").parentNode.nextSibling.nextSibling.setAttribute("class", "next");

更新:实际上,我只看到使用IE工具的空文本节点,而不是FF或Chrome。

以下是他们在IE开发人员工具中的看法:

enter image description here