简体   繁体   English

将文本链接转换为图像链接

[英]convert a text link to image link

I am in the middle of making a post system for my website, and i would like some javascript that would turn a text link like 我正在为我的网站制作一个帖子系统,我想要一些可以打开文本链接的JavaScript,例如
<a href="path/to/image.jpg">Image</a> into <a href="path/to/image.jpg">Image</a>
<a href="path/to/image.jpg"><img src="path/to/image.jpg" /></a>
but only turn it into an image link when something such as a regex recognises that the link is to an image. 但只有当诸如正则表达式之类的东西识别出该链接是指向图像时,才将其转换为图像链接。

Or i dont mind doing something like adding a data-type="image" attribute to the link, but i still need the code to turn it into an image link. 或者我不介意做一些类似向链接添加data-type =“ image”属性的操作,但是我仍然需要代码将其转换为图像链接。

$('a[href$=".png"], a[href$=".jpg"], a[href$=".gif]"').each(function(){
    $(this).html('<img src="' + $(this).attr('href') + '" />');
});

Code: http://jsfiddle.net/FcQzG/1/ 代码: http//jsfiddle.net/FcQzG/1/

I'd recommend putting a class on all of the anchors links you want to convert. 我建议您在要转换的所有锚链接上放置一个类。 Let's say you choose to use a convert class. 假设您选择使用convert类。 Then, you could use jQuery the add an img tag inside the anchor tag: 然后,您可以使用jQuery在anchor标签内添加img标签:

// for each anchor that needs converting
$('.convert').each(function() {
  // get the href of the anchor
  var href = $(this).attr('href');
  // create the string we want to append to the anchor
  var imgString = '<img src="' + href + '" alt="" />';
  // and then append it
  $(this).append(imgString);
});

@Alex solution is a better one, but if you could not add a class @Alex解决方案是更好的解决方案,但是如果您不能添加一个类

$('a').each(function(){
    var a = $(this)
    if(a.text() == 'Image')
        a.html('<img src="'+a.href+'" >')
})

http://jsfiddle.net/7AvJT/2/ http://jsfiddle.net/7AvJT/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM