使用 javascript 获取页面标题和内部图像

Get page title and inner image with javascript

我有一个 javascript,它需要一个具有特定 ID 的 link,并将图像从那个页面放到这个 links。

$('#link').each(function(){ 
    var c=$(this),
        o=c.parent(),
        url=this.href,
        m='/images/no-img.jpg'; 

    $.get(url,function(d){
      var s=m; 
      var b=$(d).find('.post-text img')||false; 
      if(b){ 
         for(var i=0,j=b.length;i<j;i++){ 
           if(!/(ucoz.net|download.png)/i.test(b[i].src)){ 
             s=b[i].src; 
             break; 
           } 
        } 
      } 
      o.prepend('<img src="'+s+'" />); 
    }); 
}); 

我想添加来自 div 的页面名称,而不是页面标题。

例如

这是 page1.html 上的 link:

<a id="link" href="/page2.html">page2</a>

这就是 page2.html 的样子

<body>
<div class="title">Page name 2</div>
<div class="post-text">
<img src="/img.jpg" />
This is a post text.
</div>
</body>

我需要用 class "title" 从 div 得到 "Page name 2" 并在 page1.html:

上得到这样的结果
<img src="/page2/img.jpg" /><a id="link" href="/page2.html">Page name 2</a>

首先,不同的元素不要使用相同的id,id必须是唯一的

讨论后得出的答案

$(document).ready(function()
{
    $('a').each(function()
    {
        var _this = $(this);
        var href = _this.attr('href');

        $.get(
            href,
            function(data)
            {
                var html = $(data);
                var titleNode = html.find('.title');
                var imageNodes = html.find('.post-text img');
                imageNodes = imageNodes.filter(function()
                {
                    return !$(this).attr('src').match(/ucoz\.net|download\.png/i);
                });

                if (imageNodes.length)
                {
                    var src = imageNodes.first().attr('src');

                    if (/.+\..+\//.test(src))
                    {
                        var imageSrc = src;
                    }
                    else
                    {
                        imageSrc = href.replace(/\.html$/, ''); // remove .html from href="/page2.html"
                        imageSrc += '/';
                        imageSrc += src.replace(/^\//, '') // remove first / to avoid //
                    }
                }
                else
                {
                    imageSrc = '/images/no-img.jpg';
                }

                _this.html(titleNode.text());
                _this.before('<img src="' + imageSrc + '">');
            }
        );
    });
});