使用URL参数模拟单击

时间:2014-10-10 14:54:11

标签: javascript tabs

我目前正在处理一个页面,其中包含使用Javascript动画/切换的4个不同标签。

我希望能够锚定这些标签,以便根据网址参数访问所选标签。

但是,目前从一个标签切换到另一个标签的唯一方法是点击它。

因此,我认为一种简单的方法是设置页面的4个不同的URL。 例如

pagename.com#1
pagename.com#2
pagename.com#3
pagename.com#4

每个数字模拟标签1到4的点击。

我能实现这样的目标吗?

非常感谢, 杰洛特

2 个答案:

答案 0 :(得分:1)

如上面的答案所述,您可以使用window.location.hash更改哈希值。但是,如果您的标签不与该功能相关联,则仅通过添加/更改散列不会更改活动选项卡。您需要做的是在您的javascript中查看当前哈希并确定要显示的相应选项卡/面板...查看此示例:

HTML:

<div id="tabs">
    <div><a href="#1">Tab 1</a></div>
    <div><a href="#2">Tab 2</a></div>
    <div><a href="#3">Tab 3</a></div>
    <div><a href="#4">Tab 4</a></div>
</div>

<div id="panels">
    <div id="1">I am a panel 1</div>
    <div id="2">I am a panel 2</div>
    <div id="3">I am a panel 3</div>
    <div id="4">I am a panel 4</div>
</div>

CSS:

#tabs > div {
    display: inline-block;
}

#panels > div {
    display: none;
}

JS:

$(document).ready(function () {
    // if you want the first one shown...
    window.location.hash = '#1';
    // initially check...
    var h = window.location.hash;
    var panel = findPanel(h);
    if (panel) {
        panelCleanUp()
        $(panel).show();
    }

    $('#tabs').on('click', 'a', function () {
        setTimeout(function () { // let the hash update...
            var hasher = window.location.hash;
            var panel = findPanel(hasher);
            if (panel) {
                panelCleanUp();
                $(panel).show();
            }
        }, 0);
    });
});


function findPanel(hasher) {
    return $('#panels ' + hasher)[0];
}

function panelCleanUp() {
    $('#panels > div').each(function () {
        $(this).hide();
    });
}

See the Fiddle

答案 1 :(得分:0)

是的!使用window.location.hash

window.location.hash = "1"; // done!