简体   繁体   English

使用jquery load()加载内容后,从页面获取所有链接;

[英]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. 这段代码的结果是:-第一个alert()返回了正确的链接数量,但是它不是DOM对象,因此我无法使用它来更改href属性:links [i] .attr('href','changed')而且我必须逐个循环获取链接,但是此方法仅返回了page.php中的第一个链接以及站点中的所有链接(不会更改)。

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: 您可以像这样更改其href

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: 如果您只需要修改已加载内容中的所有链接,请使用context ,如下所示:

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. 这将找到所有<a> ,但仅找到针对page.php返回的响应,因此仅找到您刚刚加载的锚点。 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. 格式为$(selector, context) ,如果不使用context ,则为document ,因此类似$('a')东西实际上$(document).find('a') ,为其提供除document其他上下文,您说的是$(data).find('a') ,只获取您想要的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM