将文本链接转换为图像链接 我正在为我的网站制作一个帖子系统,我希望一些JavaScript能够像BR/>一样打开文本链接。 进入 但只有当某些东西(如正则表达式)识别出链接是图像时,才能将其转换为图像链接

将文本链接转换为图像链接 我正在为我的网站制作一个帖子系统,我希望一些JavaScript能够像BR/>一样打开文本链接。 进入 但只有当某些东西(如正则表达式)识别出链接是图像时,才能将其转换为图像链接,javascript,image,Javascript,Image,或者我不介意在链接中添加data type=“image”属性,但我仍然需要代码将其转换为图像链接。$('a[href$=”.png“]、a[href$=”.jpg“]、a[href$=”.gif])。每个(函数(){ $('a[href$=".png"], a[href$=".jpg"], a[href$=".gif]"').each(function(){ $(this).html('<img src="' + $(this).attr('href') + '" />')

或者我不介意在链接中添加data type=“image”属性,但我仍然需要代码将其转换为图像链接。

$('a[href$=”.png“]、a[href$=”.jpg“]、a[href$=”.gif])。每个(函数(){
$('a[href$=".png"], a[href$=".jpg"], a[href$=".gif]"').each(function(){
    $(this).html('<img src="' + $(this).attr('href') + '" />');
});
$(this.html(“”); });

代码:

我建议在所有要转换的锚点链接上放置一个类。假设您选择使用
convert
类。然后,可以使用jQuery在锚标记内添加
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);
});
//对于每个需要转换的锚点
$('.convert')。每个(函数(){
//获取锚的链接
var href=$(this.attr('href');
//创建要附加到锚点的字符串
var imgString='';
//然后附加它
$(this).append(imgString);
});

@Alex解决方案是一个更好的解决方案,但如果您无法添加类

$('a').each(function(){
    var a = $(this)
    if(a.text() == 'Image')
        a.html('<img src="'+a.href+'" >')
})
$('a')。每个(函数(){
变量a=$(此)
如果(a.text()=“图像”)
a、 html(“”)
})

在所有给定答案中都需要jQuery。看看jsfiddles,它确实有效。