2012-04-07 22 views
0

我正在使用以下函數來加載頁面。我有大量的鏈接,不能添加到所有鏈接。如何通過jquery在所有鏈接中添加功能?

function LoadPage(url) { 
    $("#canvas").load(url); 
} 

我想一個函數,將得到所有<a>標籤href值,這個功能添加到所有鏈接就像下面:

var oP = document.getElementsByTagName("a"), 
    ctr = 0 
; 

while(ctr < oP.length) { 
    var oldHref = document.getElementsByTagName("a")[ctr].href; 

    document.getElementsByTagName("a")[ctr].href = "javascript:loadPage('" + oldHref + "');"; 
    ctr++; 
} 

我要添加的所有鏈接,但不要「INDEX。 HTML」。

+0

兩點意見您提供:1。你已經有了'document.getElementsByTagName(「A」)'存入'oP',再次稱這是你的'while'循環內的額外和不必要的處理。 2.迭代其他元素的集合通常使用for循環而不是while循環來完成,因爲您知道所需的迭代次數。 – 2012-04-07 19:55:33

回答

2

事情是這樣的:

// select all links 
$('a') 
    // check that the pathname component of href doesn't end with "/index.html" 
    .filter(function() { 
    return !this.href.pathname.match(/\/index\.html$/); 
    // // or you may want to filter out "/index.html" AND "/", e.g.: 
    // return !this.href.pathname.match(/\/(index\.html)?$/i) 
    }) 
    // add a click event handler that calls LoadPage and prevents following the link 
    .click(function(e) { 
    e.preventDefault(); 
    LoadPage(this.href); 
    }); 

既然你動態加載的頁面的部分,你需要建立事件委託來代替。具體做法取決於您使用的jQuery版本,但您將使用.on()(jQuery 1.7+)或.delegate()(jQuery 1.7之前)函數。該.on()例子是這個樣子:

$('body').on('click', 'a', function(e) { 
    if(!this.href.pathname.match(/\/index\.html$/)) { 
     e.preventDefault(); 
     LoadPage(this.href); 
    } 
}); 
+0

它加載頁面,但它不轉換新加載頁面的鏈接。我應該爲新加載的頁面做些什麼? – danny 2012-04-07 20:05:05

+0

也在新加載的頁面中包含該腳本。 – 2012-04-07 20:09:01

+1

@danny我完全忽略了這一點 - 既然你是動態加載內容,事件委派是要走的路。我更新了我的答案,使用'.on()'包含代碼 - 如果您使用的是1.7版之前的jQuery版本,則需要使用'.delegate()'。語法上的差異相對較小,所以您應該可以通過閱讀已鏈接文檔的各個部分進行轉換。 – 2012-04-07 20:12:02

0

在回答你的問題有關新加載的頁面,$.load() takes a second argument上轉換鏈接,你可以用它來應用功能如@ AnthonyGrist一個回調函數的新內容,例如:

function loadPage(url) { 
    // add a callback to $.load() to be executed for the next content 
    $("#canvas").load(url, function() { convertLinks(this); }); 
} 

function convertLinks(context) { 
    // select all links in the given context 
    $('a', context) 
    // check that the pathname component of href doesn't end with "/index.html" 
    .filter(function() { 
     return !this.href.pathname.match(/\/index\.html$/); 
     // // or you may want to filter out "/index.html" AND "/", e.g.: 
     // return !this.href.pathname.match(/\/(index\.html)?$/i) 
    }) 
    // add a click event handler that calls LoadPage and prevents following the link 
    .click(function(e) { 
     e.preventDefault(); 
     loadPage(this.href); 
    }) 
    ; 
} 

// call convertLinks on the whole document on initial page load 
$(function() { convertLinks(document); }); 

使用.on()也是一個合理的解決方案。對規則的Javascript代碼

+0

@Jorden你的代碼給我錯誤的錯誤}。你能重新檢查嗎? – danny 2012-04-07 20:47:10

+0

@danny固定。它在第三行。一般來說,Stack Overflow答案中的代碼並不意味着要被複制和粘貼,而是要在您理解後自行理解和實現。 ;) – 2012-04-07 22:00:09

+0

我得到這個錯誤this.href.pathname是未定義的 – danny 2012-04-07 23:21:55

相關問題