2011-03-31 17 views
1

div内のすべての画像を見つけて、画像タグを他のコードに置き換えたいとします。これを置き換えますとjQuery正規表現で選択してリンクを置換する

<div id='sd'> <img src="/images/panorami/53.jpg"> <img src="/images/panorami/other.jpg"> </div>

<div id='sd'> <a title="" rel="lightbox[images]" href="/images/panorami/53x.jpg"> <img src="/images/panorami/53.jpg"></a> <a title="" rel="lightbox[images]" href="/images/panorami/otherx.jpg"><img src="/images/panorami/other.jpg"></a> </div>

これはjQueryを使って行うことができますか?

答えて

4
$('#sd img').wrap(function() { 
    return $('<a />', { 
     title: '', 
     rel: 'lightbox[images]', 
     href: this.src 
    }); 
}); 

Demo。 @jensgramの回答に基づいて

+0

ニース - 私は実際により頻繁にそのコールバックを使用する必要があります。 – karim79

+0

@ [Viacheslav Molokov](http://stackoverflow.com/users/226367/viacheslav-molokov)は[指摘している](http://stackoverflow.com/questions/5498730/jquey-selecting-whit-regular-式置換リンク/ 5498901#5498901)、この解決策ではリンク内のファイル名に 'x'を追加しません。 'href:this.src'を例えばに置き換えてください。 'href:this.src.replace(/(¥.[^.]+)$/i、 'x $ 1')'を押して、目的の結果を得ます。 – jensgram

1

が、問題になっているように変更されたリンクで:

$(function() { 
    $('#sd img').wrap(function() { 
     fixed_url = $(this).attr('src').replace(/(\.[a-zA-Z]+)$/, 'x$1'); 
     return $('<a />', { 
      title: '', 
      rel: 'lightbox[images]', 
      href: fixed_url 
     }); 
    }); 
}); 

http://jsfiddle.net/sUsmA/1/

+0

+1その違いに気付かなかった。 'href:this.src.replace(/(\。[a-z] +)$/i、 'x $ 1')'それは好みの問題です。 – jensgram