我想从外部网址
找到图像src这是我的功能:
<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'
答案 0 :(得分:1)
因为数据只是html,你需要用$()包装$ .parseHTML(数据),然后执行.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>