注意:这是用于家庭作业,请仅以尊重学术诚信的方式回答。
每当我调用父节点时,它都会返回null,即使它有父节点,并且我知道如果没有父节点,它应该是这样做的。该程序应该显示DOM从父级到子级的层次结构。
var styleChange = "";
function start() {
window.addEventListener("mousedown", changeStyleTo, false);
}
window.addEventListener("load", start, false);
function changeStyleTo(e) {
e.target.setAttribute("style", "background-color: yellow; color: red");
window.addEventListener("mouseup", changeStyleBack, false);
}
function changeStyleBack(e) {
var current = e.target.cloneNode();
window.alert(current.nodeName);
var elementString = current.nodeName;
for (var i = 0; i < document.body.childElementCount; i++) {
if (current != document.body) {
elementString += current.tagName;
current = current.parentNode;
}
}
window.alert("elementString");
e.target.setAttribute("style", "background-color: white; color: black");
}
<body id="Body">
<h1 id="H1">The 23<sup>rd</sup> Psalm</h1>
<h2 id="H2">A Psalm of David.</h2>
<ol id="Ol">
<li id="Li1">
The LORD is my shepherd; I shall not want.
</li>
<li id="li2">
He maketh me to lie down in green pastures: he leadeth me beside the still waters.
</li>
<li id="li3">
He restoreth my soul: he leadeth me in the paths of righteousness for his name's sake.
</li>
<li id="li4">
Yea, though I walk through the valley of the shadow of death, I will fear no evil: for thou art with me; thy rod and thy staff they comfort me.
</li>
<li id="li5">
Thou preparest a table before me in the presence of mine enemies: thou anointest my head with oil; my cup runneth over.
</li>
<li id="li6">
Surely goodness and mercy shall follow me all the days of my life: and I will dwell in the house of the LORD for ever.
</li>
</ol>
<hr id="Hr"/>
<p id="p1">
<del id="Del">
© 1611, THE MOST HIGH AND MIGHTY PRINCE JAMES, BY THE GRACE OF GOD KING OF GREAT BRITAIN, FRANCE, AND IRELAND, DEFENDER OF THE FAITH, etc. <strong>All rights reserved.</strong>
</del>
</p>
<p id="p2">
<ins id="Ins">
This text is in the <strong>Public Domain</strong>.
</ins>
</p>
<p id="p3">
Return to
<a id="A" href="http://www.masters.edu" title="The Master's College Home Page">
The Master's College
<img src="masters.png" width="125" height="180" alt="The Master's College logo"/>
</a>
</p>
</body>
</html>
答案 0 :(得分:1)
而不是
var current = e.target.cloneNode();
写下这个:
var current = e.target;
此外,您的循环未进行优化,请移除循环并将if
条件修改为while
循环。