假设我有一个主页,其中包含指向第二页的链接,该第二页包含某种内容,例如<details>
元素。现在,第二页中的<details>
元素默认关闭,但我希望主页中的链接重定向到<details>
元素并打开它。
我想用基本的html / css和javascript来做到这一点。以下是我到目前为止的情况:
home.html的
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var a = document.getElementById("mylink");
a.onclick = function() {
var b = document.getElementById("mydetails");
b.open = true;
b.style.color = "red"; // just to try another property
return false;
}
}
</script>
</head>
<body>
<h1>Home Page</h1>
<h2><a id="mylink" href="second_page.html#mydetails">Go to 2nd page</a></h2>
</body>
</html>
second_page.html
<html>
<body>
<h1>2nd page</h1>
<details id="mydetails" open="false">
<summary>Hello,</summary>
</details>
</body>
</html>
不幸的是,代码会运行但是当我点击主页中的链接时,第二页中的<details>
无法打开。我怎么能这样做?
如果我可以将链接和目标元素的ID作为参数传递给JS函数,那么
点数。
相关问题:
答案 0 :(得分:1)
function(link,target){
//set the click function of the given id (link)
$('#'+link).click(function() {
//get the details panel from the next page
var details = $(target+'#mydetails');
//set its state to true
details.open = true;
//redirect to that page
window.location.replace(details);
});
}
这些方面的东西应该有效。 这是使用jquery,希望这没关系。
答案 1 :(得分:1)
您无法使用Javascript修改其他未处于活动状态的页面。 Javascript只能在活动页面上运行,并且可以修改活动页面的DOM。您必须将值发送到下一页。
要发送数据的HTML5会话存储:
home.html
<script type="text/javascript">
window.onload = function() {
var a = document.getElementById("mylink");
a.onclick = function() {
localStorage.setItem("open", "true");
}
}
</script>
second_page.html
<script>
var val = localStorage.getItem("open");
if (val == "true") {
var b = document.getElementById("mydetails");
b.open = true;
b.style.color = "red";
localStorage.removeItem("open");
}
</script>