[英]Swap image src after ajax request using jQuery
我需要使用jQuery
交換 img 元素的圖像 src。 我使用$.getJSON()
獲取圖像,每次都是不同的。 我已經使用hover
將此交換鏈接到<li>
元素的 hover,但有時當圖像更改或圖像未正確加載到第一個 ZE0542F579DF8E8138ADE69F8F5310BF 時,它會有點滯后。 我需要一個有效的解決方案來幫助我解決問題。 這是代碼:
HTML:
<div class="col-md-2 col-lg-2 text-right portfolio-thumb">
// here I used a static img tag, but I've opted to append it everytime.
<img class="img-fluid portfolio-nav-thumb" width="80" src="">
</div>
<div class="col-md-4 col-lg-4 portfolio-nav">
<ul class="navbar-nav ml-auto">
<?php if( $portfolio->have_posts() ): while( $portfolio->have_posts() ): $portfolio->the_post(); ?>
<li class="nav-item portfolio-nav-el"><a data-id="<?php echo get_post_thumbnail_id(); ?>" class="nav-link portfolio-nav-link" href="<?php the_permalink(); ?>"><?php the_title('<h4>', '</h4>'); ?></a></li>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</ul>
</div>
JS:
$('.portfolio-nav-el').on('hover', function(e){
e.preventDefault();
// here I empty the img container div
$('.portfolio-thumb').empty();
var id = $(this).children('.portfolio-nav-link').attr('data-id');
//console.log(id);
$.getJSON('https://localhost/wordpress/wp-json/wp/v2/media/'+id, function(response){
// here I'm adding the img element to the parent container div
$('.portfolio-thumb').html('<img class="img-fluid portfolio-nav-thumb" src="'+ response.source_url +'" width="80">');
});
});
預加載或淡入淡出解決方案可以嗎?
$(document).on('hover', '.portfolio-nav-el', function() {
//Enter your code here...
});
此代碼適用於在 ajax 之后創建的元素
我想你自己回答了。 預加載是 imo 的最佳解決方案。 我可能會為列表中的所有項目加載縮略圖。 也許在 base64 形式中,將其存儲在每個項目的適當數據屬性中,然后在 hover 上,在“.portfolio-thumb”元素的 src 中使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.