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

Get page title and inner image with javascript

本文关键字:内部 图像 标题 javascript 获取 使用      更新时间:2023-09-26

我有一个javascript,它获取一个具有特定id的链接,并将图像从该页面放置到该链接。

$('#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中的页面名称,但不添加页面标题。

例如

这是一个页面上的链接1.html:

<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>

我需要用类"title"从div中获得"Pagename2",并在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 + '">');
            }
        );
    });
});