Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jquery将href中的标记的图像URL转换为标记?_Javascript_Jquery_Html_Image_Anchor - Fatal编程技术网

Javascript 如何使用jquery将href中的标记的图像URL转换为标记?

Javascript 如何使用jquery将href中的标记的图像URL转换为标记?,javascript,jquery,html,image,anchor,Javascript,Jquery,Html,Image,Anchor,我的HTML包含多个标签,在href属性中有图像URL。我想将其转换为图像alt属性中锚定集的文本,如下图所示 <a href="https://i.stack.imgur.com/va6oM.jpg">jpg image</a> <a href="https://i.stack.imgur.com/4aCuV.png">png image</a> <a href="http://stackoverflow.com">stackover

我的HTML包含多个标签,在href属性中有图像URL。我想将其转换为图像alt属性中锚定集的文本,如下图所示

<a href="https://i.stack.imgur.com/va6oM.jpg">jpg image</a>
<a href="https://i.stack.imgur.com/4aCuV.png">png image</a>
<a href="http://stackoverflow.com">stackoverflow</a>
应转换为

<img src="https://i.stack.imgur.com/va6oM.jpg" alt="jpg image" />
<img src="https://i.stack.imgur.com/4aCuV.png" alt="png image" />
<a href="http://stackoverflow.com">stackoverflow</a>

如何完成这项工作?

您可以使用jQuery选择锚定标记包含图像URL

或者在中使用正则表达式

然后,您需要使用将选定标记转换为新标记

$a.filterfunction{ 返回此.href.match/.jpg | JPEG | png | gif$/; }.replaceWithfunction{ 回来 };
您应该迭代每个标记

$('a').each(function(i, a) {
   var src, txt;

   src = $(a).attr('src');
   txt = $(a).text(); // or .html()

   // now lets replace the <a> with <img>
   $(a).replaceWith('<img src="' + src + '" alt="' + txt + '">');
});
希望这将帮助您使用匹配的

[attr$=值]

表示属性名为attr且最后一个 value以value作为后缀

作用{ 变量锚=$[href$='.jpg'],[href$='.png'], i=0, len=锚固件长度; 对于i,len;i$("a").filter(function(){ return this.href.match(/.(jpg|JPEG|png|gif)$/); }).someFunction();
selectedAnchor.replaceWith(function(){
  return '<img src="'+ this.href +'" alt="'+ this.textContent +'" />';
});
$('a').each(function(i, a) {
   var src, txt;

   src = $(a).attr('src');
   txt = $(a).text(); // or .html()

   // now lets replace the <a> with <img>
   $(a).replaceWith('<img src="' + src + '" alt="' + txt + '">');
});