簡體   English   中英

使用jQuery將HTML標簽包裝在另一個標簽中

[英]Wrap an HTML tag in another using jQuery

http://jsfiddle.net/62w8f00o/

我有一些這樣的HTML:

<div><img src="http://i.imgur.com/4pB78ee.png"/></div>

並且我想使用jQuery將img標簽包裝為a標簽,如下所示:

$(function() {
  var a = '<a href="http://i.imgur.com/4pB78ee.png"></a>';
  // want to wrap the <img> with the above <a> here
});

最終結果將是這樣的:

<div>
    <a href="http://i.imgur.com/4pB78ee.png">
        <img src="http://i.imgur.com/4pB78ee.png"/>
    </a>
</div>

如何用a包裝我的img

您可以使用jQuery wrap函數

$( "img" ).wrap( "<a href=\"http://i.imgur.com/4pB78ee.png\"></a>" );

將上面的$( "img" )替換為實際的選擇器,您不想選擇網頁中的所有圖像。

小提琴: http : //jsfiddle.net/5c5bffh1/

語法為:

$('.inner').wrap('<a class="outer"></a>);

因此,它將類似於:

$('img').wrap('<a href="http://i.imgur.com/4pB78ee.png"></a>')

使用jQuery .wrap()

$(function() {
  var a = '<a href="http://i.imgur.com/4pB78ee.png"></a>';
  $('img').wrap(a);  
});

更新的小提琴: http : //jsfiddle.net/62w8f00o/1/

暫無
暫無

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

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