2012-08-27 46 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

相關問題