使用jQuery从外部URL获取图像src [英] Get image src from external url using jQuery

查看:84
本文介绍了使用jQuery从外部URL获取图像src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从外部网址获得的图片src

I'm looking to find image src from external url

这是我的功能:

<script>
function sompret_image_creator(url, ptitle)
{
    $.ajax(
        { 
        url: url, 
        success: function(data) {
            var img = $.parseHTML( data ).find("img"), 
                len = img.length; 
            if( len > 0 ){
                var src = img.first().attr("src"); // get id of first image
            } else {
                console.log("Image not found");
            }
            console.log(src);

            image_tag='<img src="'+src+'" alt="'+ptitle+'"/>';
            return image_tag;
        } 
    });
}
</script>

我遇到此错误

未捕获的TypeError:对象[object Array]没有方法'find'

推荐答案

由于数据仅为html,因此需要用$()包装$ .parseHTML(data),然后再执行.find()

Because the data is only html, you need to wrap the $.parseHTML( data ) with $() and then do .find()

<script>
function sompret_image_creator(url, ptitle)
{
    $.ajax(
        { 
        url: url, 
        success: function(data) {
            var html = $.parseHTML( data ), 
                img = $(html).find("img"),
                len = img.length; 
            if( len > 0 ){
                var src = img.first().attr("src"); // get id of first image
            } else {
                console.log("Image not found");
            }
            console.log(src);

            image_tag='<img src="'+src+'" alt="'+ptitle+'"/>';
            return image_tag;
        } 
    });
}
</script>

这篇关于使用jQuery从外部URL获取图像src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆