js获取html页面代码中图片地址的实现代码
第一种方法:js通过正则实现
/**
*获取html代码中图片地址
*@paramhtmlstr
*@returns{Array}
*/
functiongetimgsrc(htmlstr){
varreg=/)/gim;
vararr=[];
while(tem=reg.exec(htmlstr)){
arr.push(tem[2]);
}
returnarr;
}
第二种方法:jquery实现
varimg=$(this).find("img").attr("src");//这个是获得相对路径prospertu
//alert($(this).find("img").prop("src"));这个是获得完整路径包括http://
js在获取图片的src是相对路径
js在获取src时或同时获取到域名路径;如图片路径是http://dh.wk163.commall/kmenus/001.png,用obj.src或获取到http://localhost/http://dh.wk163.commall/kmenus/001.png,但是通常只获取相对路径就可以了。做此记录。
functionshowSelected(obj) { varrootpath='http://localhost/'; res=obj.src.replace(rootpath,''); //分离路径和图片 document.getElementById("cate_img_src").src=obj.src; }
这篇文章就介绍到这,需要的朋友可以参考一下。