Home > Web Front-end > JS Tutorial > How to directly obtain the image address in the web page using js

How to directly obtain the image address in the web page using js

php中世界最好的语言
Release: 2018-03-28 13:32:21
Original
5812 people have browsed it

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=(&#39;|")?([^&#39;"]+)(&#39;|")?(?:\s+|>)/gim; 
  var arr = []; 
  while (tem = reg.exec(htmlstr)) { 
    arr.push(tem[2]); 
  } 
  return arr; 
}
Copy after login

The second method:jqueryimplementation

 var img = $(this).find("img").attr("src");//这个是获得相对路径 prospertu
        //alert($(this).find("img").prop("src"));这个是获得完整路径 包括http://
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template