Home  >  Article  >  Web Front-end  >  Use js to quickly get the address of the image in the html page

Use js to quickly get the address of the image in the html page

php中世界最好的语言
php中世界最好的语言Original
2018-03-17 11:08:223656browse

This time I will bring you how to use js to quickly get the address of the image in the html page, and how to use js to quickly get the address of the image in the html page. What are the precautions?The following is a practical case, let's take a look take a look.

This article mainly introduces the implementation code for js to obtain the image address in html code. Friends who need it can refer to it

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; 
}

Second method: jquery implementation

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

js obtains the src of the image as a relative path

js obtains the domain name path when obtaining the src or at the same time; such as the picture The path is mall/kmenus/001.png, use obj.src or get http://localhost/mall/kmenus/001.png, but usually only get the relative path. 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 the React BootStrap framework

Set cookie expiration, automatic update and automatic acquisition

How to make the files packaged by webpack smaller after compression

The above is the detailed content of Use js to quickly get the address of the image in the html page. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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