2012-04-07 23 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

相关问题