【发布时间】:2015-02-23 03:49:13
【问题描述】:
我有一个 html 文档,正文中有 4 个 <p>-tags。我有一个单独的 js 文件并想使用 javascript 来:
在第 1 和第 3 段中创建和放置链接。
创建一个在显示和隐藏文本之间切换的函数 每个链接下面的段落,当对应的链接是 活性。段落应该从一开始就隐藏起来。
我无法使用切换功能。该页面仍然显示从一开始的所有段落,当我单击链接时,页面只会闪烁一毫秒。
下面是我的代码。我是初学者,我知道这是不好的代码,但我只想让它成为一个工作脚本。我不知道为什么它不起作用,因此非常感谢擅长此操作的人的帮助。
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<p>When this link is activated..</p>
<p id="displayPara">..I want this hidden paragraph to be revealed.</p>
<p>And if the link below is clicked..</p>
<p>..this paragraph should be revealed.</p>
<script type="text/javascript" src="showHide.js"></script>
</body>
</html>
The JS-file:
//Creates the 2 links and puts them where I want them in the document body.
function Links() {
a = document.createElement("a");
a.setAttribute("href", "showHide.html");
a.setAttribute("id", "firstLink");
a.innerHTML = "<br></br>Show paragraph";
document.getElementsByTagName("p")[0].appendChild(a);
a2 = document.createElement("a");
a2.setAttribute("href", "showHide.html");
a2.setAttribute("id", "secondLink");
a2.innerHTML = "<br></br>Show paragraph";
document.getElementsByTagName("p")[2].appendChild(a2);
}
Links();
/*I want this function to toggle between showing and hiding the 2nd and 4th paragraphs when the links are clicked.
I tried with the first link first and it doesn't work.*/
a.onclick = function toggle() {
displayPara = document.getElementById("displayPara");
firstLink = document.getElementById("firstLink");
if(displayPara.style.display == "block") {
displayPara.style.display = "none";
firstLink.innerHTML = "Show paragraph"
}
else {
displayPara.style.display = "block";
firstLink.innerHTML = "Hide paragraph";
}
}
【问题讨论】:
-
<br>是一个空标签,</br>是一个被忽略的幻影。 title 元素不能为空。
标签: javascript onclick toggle show-hide