携带变量从外部链接到页面,并插入jQuery脚本onload

Carrying Variable from external link to page and plugging into jQuery script onload

本文关键字:插入 jQuery onload 脚本 变量 从外部 链接      更新时间:2023-09-26

我有这个jQuery显示/隐藏的内容取决于所单击的列表项。我还希望能够在此页面登陆时显示特定的内容,这取决于用户在另一个页面上单击的链接。

我知道要做到这一点,我必须以某种方式从另一个链接中携带变量,并使其充当变量。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>    
<script type="text/javascript"> 
$(document).ready(function() {
$('#side_nav ul li a').click(function() {
    $('#side_nav ul li.current').removeClass('current');
    $(this).parent().addClass('current');
    var filterVal = $(this).attr('class');
        $('#content div.section').each(function() {
            if($(this).hasClass(filterVal)) {
                $(this).fadeIn(200);
            } else {
                $(this).hide();
            }
        });
    return false;
});
});
</script>

我试过在单独页面上的链接的url末尾添加#desired_content,我知道使用window.location。哈希,我可以把哈希表作为变量拉进来但我不知道具体怎么做

请帮助。

编辑:我把这个添加到外部页面:

<li><a href="./about.html#how_it_works">HOW IT WORKS</a></li>

和这个到目标页面,只是为了测试是否添加类

<script type="text/javascript"> 
$(document).ready(function() {
    var myHash = window.location.hash;
    if( myHash == "#how_it_works" ){
        $('#content div.how_it_works').addClass('test');
    }else if( myHash == "#option2" ){
        // fade in option2
    }

});     
</script>

我不明白为什么这不起作用

哈希url主要用于页面内锚标记(返回顶部等),因此我建议使用哈希url将某人引导到页面的某个部分非常有意义。

我所做的是,一旦在页面上,通过window.location.hash获取哈希URL,并基于此字符串操作页面。

var myHash = window.location.hash;
if( myHash == "#desired_content" ){
// fade in option1
}else if( myHash == "#option2" ){
// fade in option2
}

我建议将变量存储在第一页的localStorage上,然后在第二页从localStorage加载变量。它将比传递哈希URL更简单,这不是正确的目的。

第一页
<a href="secondPage.html" id="link">Go to second page</a>
<script type="text/javascript"> 
$(document).ready(function() {
$('#link').click(function(){
    // set your variable when someone click the link
    localStorage.setItem("myVariable", "someValue");
});
});
</script>

第二页

<script type="text/javascript"> 
$(document).ready(function() {
var yourVariable = localStorage.getItem("myVariable");
// do your stuff according to this variable that passed from firstpage
//...
});
</script>