This time I will show you how to directly obtain the image address in the webpage with js. What are the precautions for js to directly obtain the address of the image in the webpage. The following is a practical case. Let’s take a look. take a look.
The first method: js is implemented through regular expressions
/** * 获取html代码中图片地址 * @param htmlstr * @returns {Array} */ function getimgsrc(htmlstr) { var reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim; var arr = []; while (tem = reg.exec(htmlstr)) { arr.push(tem[2]); } return arr; }
The second method:jqueryimplementation
var img = $(this).find("img").attr("src");//这个是获得相对路径 prospertu //alert($(this).find("img").prop("src"));这个是获得完整路径 包括http://
js is used to obtain the image src is a relative path
js gets the domain name path when getting src or at the same time; if the image path is mall/kmenus/001.png, use obj.src or get http://localhost/ mall/kmenus/001.png, but usually just getting the relative path is enough. Make this record.
<img src="mall/kmenus/001.png" onclick="showSelected(this)"> function showSelected(obj) { var rootpath='http://localhost/'; res=obj.src.replace(rootpath,''); //分离路径和图片 document.getElementById("cate_img_src").src=obj.src; }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use CORS of the Koa2 framework to complete cross-domain ajax requests
http in Vue2.0 Request and loading display
The above is the detailed content of How to directly obtain the image address in the web page using js. For more information, please follow other related articles on the PHP Chinese website!