【问题标题】:jquery changes execute on different html pagejquery更改在不同的html页面上执行
【发布时间】:2015-04-27 16:50:21
【问题描述】:

有没有办法让一个 html 更改上的链接在单独的 html 页面中激活 jquery 更改?我认为this 问题是相关的,但我并不完全理解。

当我单击“page1.html”中的链接时,我想打开链接并对“page2.html”进行更改。

示例:

page1.html

<a href="page2.html#about" class="tab-link">Link to Services</a>

page2.html

<div id="tab1" class="tab-content">
    <h3>Services</h3>
</div>
<div id="tab2" class="tab-content">
    <h3>Contact</h3>
</div>

script.js

$(".tab-link").click(function(){
    $("#tab1").addClass("active");
});

【问题讨论】:

  • JavaScript 在浏览器中以 jQuery 等语言使用时仅适用于浏览器中当前加载的页面。只要您刷新、重新加载或在您的情况下加载页面,就不会出现任何更改。
  • @Djave 虽然是真的,但这与问题或答案没有任何关系

标签: jquery html css


【解决方案1】:

在第 1 页:

<a href="page2.html#services" class="tab-link">Link to Services</a>
<a href="page2.html#contact" class="tab-link">Link to Contact</a>

当在您的网站上单击这些链接时,第 2 页将在浏览器中加载一个 URL,例如 http://www.yourdomain.com/page2.html#services。然后,您可以在 javascript 中使用 window.location.hash 获取 #services 部分。所以为了简化,我在你的标签上设置了 ID 以匹配链接中的那个位:

在第 2 页:

<!-- I set the ID's to match the hash on the above links -->
<div id="services" class="tab-content">
    <h3>Services</h3>
</div>
<div id="contact" class="tab-content">
    <h3>Contact</h3>
</div>

以及第 2 页的 JS:

$(document).ready(function(){
    // window.location.hash returns the '#...' part of the page URL
    // which from the html I provided, would be #services or #contact.
    // We check to make sure there is one first, and then set your 'active' class
    if(window.location.hash){
        var tabID = window.location.hash;
        $(tabID).addClass('active'); 
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    • 2014-03-25
    • 1970-01-01
    相关资源
    最近更新 更多