簡體   English   中英

如何通過jQuery將元素插入現有HTML?

[英]How to insert element into existing HTML by jQuery?

我有HTML代碼段:

<div class="main-photo" style="height: 304.875px;">
     <img class="big-thumb" src="blob:http://localhost:8080/cf4ffcff-7322-44dc-8c46-3c29ef165378" style="top: -27px;">
</div>

當鼠標懸停時,我需要結果:

<div class="main-photo" style="height: 304.875px;">
    <a class="fancybox fancybox.iframe" href="blob:http://localhost:8080/cf4ffcff-7322-44dc-8c46-3c29ef165378">
         <img class="big-thumb" src="blob:http://localhost:8080/cf4ffcff-7322-44dc-8c46-3c29ef165378" style="top: -27px;">
    </a>
</div>

當將鼠標懸停在圖片上時,我嘗試使用jQuery這樣的方法(存根提示):

$('.main-photo').hover(function() {
    $('.main-photo ').append()..attr('class', 'fancybox fancybox.iframe');
});

但沒有用

您將需要包裝/解開anchor元素,從圖像中動態獲取anchor的源會更好。

 $('.main-photo').hover(function() { var $img = $(this).find('img'), $a = $('<a />', { 'class': 'fancybox fancybox.iframe', href: $img.attr('src') }); $img.wrap($a) }, function() { $(this).find('img').unwrap() }); 
 .main-photo { border: 1px solid grey; } .fancybox { border: 1px solid green; background-color: lightblue; display: inline-block; padding: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="main-photo" style="height: 304.875px;"> <img class="big-thumb" src="//placehold.it/64X64" style="top: -27px;"> </div> 

您可能要嘗試以下操作:

$('.main-photo').hover(function() { 
   $(this).find("img").wrap('<a class="fancybox fancybox.iframe" href="blob:http://localhost:8080/cf4ffcff-7322-44dc-8c46-3c29ef165378"></a>');
}, function(){
   $(this).find('img').unwrap();
});
$('.main-photo').hover(function() {
    $('.main-photo ').append()..attr('class', 'fancybox fancybox.iframe');
});

嘗試將您的代碼更改為此

$('.main-photo').hover(function() {
    $('.main-photo ').append("<a class="fancybox fancybox.iframe" href="blob:http://localhost:8080/cf4ffcff-7322-44dc-8c46-3c29ef165378">");
    $(".big-thumb").append("</a>");
});

暫無
暫無

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

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