簡體   English   中英

將文本鏈接轉換為圖像鏈接

[英]convert a text link to image link

我正在為我的網站制作一個帖子系統,我想要一些可以打開文本鏈接的JavaScript,例如
<a href="path/to/image.jpg">Image</a>
<a href="path/to/image.jpg"><img src="path/to/image.jpg" /></a>
但只有當諸如正則表達式之類的東西識別出該鏈接是指向圖像時,才將其轉換為圖像鏈接。

或者我不介意做一些類似向鏈接添加data-type =“ image”屬性的操作,但是我仍然需要代碼將其轉換為圖像鏈接。

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

代碼: http//jsfiddle.net/FcQzG/1/

我建議您在要轉換的所有錨鏈接上放置一個類。 假設您選擇使用convert類。 然后,您可以使用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解決方案是更好的解決方案,但是如果您不能添加一個類

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM