0

我正在尝试延迟链接属性,以便在内容淡出后应用它。但是添加超时功能不起作用。有任何想法吗?

$(function () {
    $(".layout a").click(function () {
        setTimeout(function () { $("link:first").attr("href", $(this).attr('rel')); }, 500)
    $.cookie("Layout", $(this).attr('name'), { expires: 365, path: '/media', secure: true });
    $('.content, .searchresults').fadeOut(500).delay(500).fadeIn(275);
        window.scrollTo(0, 0); // Scroll Window back to Top
        return false;
    });
});
4

2 回答 2

0

您可以为 fadeOut 函数分配回调,而不是设置超时以对应延迟:

$(".layout a").click(function () {
    $.cookie("Layout", $(this).attr('name'), { expires: 365, path: '/media', secure: true });
    $('.content, .searchresults').fadeOut(500, function() {
        $("link:first").attr("href", $(this).attr('rel'));
    }).fadeIn(275);

    window.scrollTo(0,0);
    return false;
}

查看 jQuery 参考以获取更多信息:http ://api.jquery.com/fadeOut/

不过,我通常几乎没有运气通过 javascript 更改通过链接标记加载的样式表。

于 2013-01-29T21:02:01.957 回答
0

你被范围this比时间打败更多。

表达方式

$(this).attr('rel');

本身很好,但在setTimeout函数内部,this不再引用单击的元素。

好消息是,通过在仍然引用正确对象$(this).attr('rel')的合适点分配局部变量,可以轻松解决问题。this

此外,为了保证时间,您可以移动可能的 setTimeout 函数,使其成为fadeOut()表达式的回调。

将这两件事加在一起,代码如下:

$(function () {
    $(".layout a").click(function () {
        var rel = $(this).attr('rel');
        $.cookie("Layout", $(this).attr('name'), { expires: 365, path: '/media', secure: true });
        $('.content, .searchresults').fadeOut(500, function() {
            $("link:first").attr("href", rel);
        }).delay(500).fadeIn(275);
        window.scrollTo(0, 0); // Scroll Window back to Top
        return false;
    });
});
于 2013-01-29T21:12:25.667 回答