如何使用jQuery创建这些动态锚链接?

时间:2010-10-15 15:22:10

标签: javascript jquery

我最近发现了一个非常酷的网站!例如:

  • 有两个链接“猫”和“狗”。
  • 有两个DIV容器,id =“catImage”和id =“dogImage”
  • 初始网址类似于http://mysite.com/#cat
  • 最初,猫图像可见
  • 点击狗链接会淡出catImage div并淡入dogImage div
  • 此外,它会将浏览器网址中的锚点更改为:http://mysite.com/#dog
  • 使用htt://mysite.com/#dog打开网站最初会显示狗图像

这可以使用jQuery吗?我将如何扫描该锚点,以及在单击链接时如何调用函数而不会导致链接跟随某个URL?我是一个客观的家伙,对JS一无所知......希望我的问题对你来说不是太愚蠢。

3 个答案:

答案 0 :(得分:2)

使用此标记:

<div id="images">
    <div id="catImage">some cat image here</div>
    <div id="dogImage" style="display:none;">some dog image here</div>
</div>
<div id="anchors">
    <a href="#cat">catImage anchor</a>
    <a href="#dog">dogImage anchor</a>
</div>

并使用此js(假设jquery 1.4.x)

    $(function () {

        $("#anchors a").click(function () {
            // send the index of the anchor to the function
            fadeImage($(this).index());
        });

        var hash = window.location.hash;
        if (hash) {

            var elementId = "#" + hash.substring(1) + 'Image';
            var $div = $(elementId);

            // check if this element exists, and if so, send that index to the function
            if ($div.length) {
                fadeImage($div.index());
            }

        }

    });

    function fadeImage(index) {
        $("#images div:eq(" + index + ")").fadeIn().siblings().fadeOut();
    }

并解释这里发生了什么:

我正在使用jquery index()函数来获取元素相对于其兄弟的索引。然后我将该索引传递给fadeImage函数,该函数找到相同的索引div并将其淡入。通过使用链接,我然后查看该div的兄弟将其淡出。如果你有超过2个div来淡出,这很有用。

对于anchor / hash用法,我只找到具有匹配id的div并获取其索引,并将其传递给相同的函数。

jQuery文档可以比我更好地解释各种方法。

答案 1 :(得分:1)

更新:哦,我忘记了,如果您想使用它,显然应该阅读tutorial about jQuery

您可以通过window.location.hash获取并设置网址的哈希值,例如

alert(window.location.hash);
//and 
window.location.hash = 'test'

你应该read about events才能完全理解它是如何运作的。 event对象提供了preventDefault()方法,该方法完全按照其说法执行(防止默认行为)。

E.g。用jQuery:

$('a').click(function(e) {
    //Do something..
    // prevent to follow the link
    e.preventDefault();
});

答案 2 :(得分:1)

使用location.href,您可以在javascript中获取完整的URL。

您可以使用子字符串或字符串替换您的域名,其余的将是您的参数狗或猫。

获得参数时。

jquery函数如show(); hide();展示猫和藏狗。

通过添加或删除样式,您也可以更改图像

.add()就在那里

addClass removeClass在那里

http://mattwhite.me/11tmr.nsf/D6Plinks/MWHE-695L9Z

http://rockmanx.wordpress.com/2008/10/03/get-url-parameters-using-javascript/

http://api.jquery.com/show/

http://api.jquery.com/addClass/