2017-02-25 70 views
0

比方说,我有一个主页,其中包含指向具有某种内容的第二页的链接,例如<details>元素。现在,第二页中的<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>在上第二页不会打开。我怎么能解决这个问题?

附加点,如果我可以作为参数传递给JS函数链接和目标元素的ID。

相关问题:

  1. How to use a link to call JavaScript?,从那里我得到了我的大部分代码
  2. Automatically open <details> element on ID call,这似乎是我想达到的目标,但我不知道如何得到它的工作

回答

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> 
+0

谢谢,它工作!我还有一个额外的问题:如果我从'

'元素中删除'open =“false”',为什么它不再工作? –

+0

@PierPaolo你的意思是''是这样的吗?没有'open'属性? – Ayush

+1

@PierPaolo它不会工作,因为没有像'open'这样的属性需要修改。 – Ayush

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,希望没关系。

+0

在我选择的解决方案,我比较熟悉的结束,但感谢你的帮助仍然! –

相关问题