开发者

Getting all of links from page after load content with jquery load();

After load content to page using

div.load('page.php');

I need get all of links from page to change them. So I wrote this:

div.load('page.php', function() {
    links = $('a');
    alert(links.length);

    for(i=0 ; i<links.length ; i++
    {
        link = $('a:nth-child('+(i+1)+')');
        alert(link.attr('href'));
    }
});

The result of this code is开发者_运维百科: - first alert() returned correct links quantity, but it's not a DOM objects, so I can't change href attribute using it: links[i].attr('href', 'changed') and I have to getting links in loop one by one, but this method returned only first link from page.php and all of links from site which will not changed.

Have someone any idea how do it?


You can do like:

div.load('page.php', function() {
    $('a').each(function(index){
      alert($(this).attr('href'));
    });
});

You can change their href like:

div.load('page.php', function() {
    $('a').each(function(index){
      $(this).attr('href', 'whatever');
    });
});


If you need to modify all the links only in the content that was loaded, use a context, like this:

div.load('page.php', function(data) {
  $('a', data).attr('href', '#');
});
//or, if they're interdependently changed, something like this...
div.load('page.php', function(data) {
  $('a', data).attr('href', function(i, href) {
    return href + "?tracking=1"; //append ?tracking=1
  });
});

This finds all <a>, but only inside the response that came back for page.php, so only the anchors that you just loaded. The format is $(selector, context), if you leave context off, it's document, so something like $('a') is really $(document).find('a'), giving it a context other than document, you're saying $(data).find('a'), getting only the links you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜