简体   繁体   English

在 ajax 请求后使用 jQuery 交换图像 src

[英]Swap image src after ajax request using jQuery

I need to swap the image src of an img element using jQuery .我需要使用jQuery交换 img 元素的图像 src。 I fetch the images using $.getJSON() and this is a different one every time.我使用$.getJSON()获取图像,每次都是不同的。 I've chained this swap to the hover of an <li> element using jQuery, but sometimes it will lag a bit when the image is changed or the image isn't loaded correctly on the first hover.我已经使用hover将此交换链接到<li>元素的 hover,但有时当图像更改或图像未正确加载到第一个 ZE0542F579DF8E8138ADE69F8F5310BF 时,它会有点滞后。 I need a valid solution that can help me to do the trick.我需要一个有效的解决方案来帮助我解决问题。 Here is the code:这是代码:

HTML: 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: 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">');
    });
});

A preload or a fade solution can be fine?预加载或淡入淡出解决方案可以吗?

$(document).on('hover', '.portfolio-nav-el', function() {
   //Enter your code here...
});

This code will work on the elements that are created after ajax此代码适用于在 ajax 之后创建的元素

I think you answered yourself.我想你自己回答了。 The preload is the best solution imo.预加载是 imo 的最佳解决方案。 I would probably load thumbnails for all items in the list.我可能会为列表中的所有项目加载缩略图。 Maybe in base64 form, store it in propriate data attribute of each item and then, on hover, use it in src of your '.portfolio-thumb' element.也许在 base64 形式中,将其存储在每个项目的适当数据属性中,然后在 hover 上,在“.portfolio-thumb”元素的 src 中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM