2012-08-27 44 views
0

我正在尝试重定向网页上的链接,在这个简单的示例中,它只是通过简单的检查来设置cookie。将网页上的链接重定向到JavaScript函数

不确定这是否是正确的方式来照顾这种情况,如果我遇到问题时有几个链接与“download_link”类,但即使是现在,只有这样的链接之一,目标设置为未定义,它看起来像调用重定向器中的$(this)实际上是指向整个HTML文档,而不仅仅是我试图改变的元素...

function redirect_link(e, destination) { 
     if ($.cookie("contact_set") == "true") { 
      window.location.href = destination; 
     } else { 
      alert("cookie not set"); 
     } 
    } 
    function redirector(destination) { 
     alert("creating redirector to "+destination); 
     return function(e) {redirect_link(e, destination)}; 
    } 
    $(document).ready(function() { 
     $('.download_link').click(redirector($(this).attr("href"))); 
     $('.download_link').attr("href", "#"); 
    }); 

回答

2

您正在访问文档的ready回调范围$(this),因此$this指向一个HTMLDocument对象!

$(document).ready(function() { 
    var $downloadLnk = $('.download_link'); 
    $downloadLnk.click(redirector($downloadLnk.attr("href"))); 
    $downloadLnk.attr("href", "#"); 
}); 

当你要求它在您的评论:

$(document).ready(function() { 
    $('.download_link').each(function() { 
    var $lnk = $(this); 
    $lnk.click(redirector($lnk.attr("href"))); 
    $lnk.attr("href", "#"); 
    }); 
}); 
+0

这似乎现在运行良好,而我只有这样的链接之一......我该怎么做来处理更多的链接? – Matthieu

+0

如果你可以用选择器标识每个链接,你可以使用jQuery的'each'功能。 – ComFreek

+0

$('。download_link')是选择器...让我试试你刚刚添加的内容... – Matthieu

1
$(function() { // <-- Short for $(document).ready(function() { 
    $('.download_link').each(function() { 
     var $this = $(this); 

     $this.click(redirector($this.attr("href")); 
     $this.attr("href", "#"); 
    }); 
}); 
0

您可以随时使用目标:

$(document).ready(function() { 
    $('.download_link').on('click', redirector); //bind to function 
    $('.download_link').attr("href", "#"); 
});​ 

function redirector(event) { 
    alert("creating redirector to "+event.target.href); //event.target 
    return function(e) {redirect_link(e, destination)}; 
} 

但是通过您的链接被点击的HREF会的时间无论您使用什么,都可以使用#,因为您在点击处理程序之后的下一行将其设置为该值。

+1

不会到达重定向器时,href已被重置为“#”? – Matthieu

+0

是的,但无论如何它会这么做!只有它提醒正确的值的原因是因为该函数没有被绑定到处理函数中,它会立即执行,因为它有附加的假设,假设它被绑定在'click'中,所以我不明白你是什么试图做什么? – adeneo

+0

试图删除href中的目标,并用一个onClick处理程序取而代之,该处理程序可以执行其他操作并最终重定向到用户尝试访问的内容。 – Matthieu

相关问题