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

标签 javascript php jquery html css

我需要使用 jQuery 交换 img 元素的图像 src .我使用 $.getJSON() 获取图像每次都是不同的。我已将此交换链接到 hover<li>元素使用 jQuery,但有时当更改图像或第一次悬停时图像未正确加载时它会有点滞后。我需要一个有效的解决方案来帮助我解决问题。这是代码:

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 之后创建的元素

关于javascript - 使用jQuery在ajax请求后交换图像src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837620/

相关文章:

javascript - 如何防止表单提交后重定向?

javascript - 更改div内容onclick

php - 加载所有javascript后如何输出DOM?

javascript - Phonegap 事件在线/离线不工作

java - 将 java 纪元字符串与 php 纪元日期进行比较

javascript - 切换变量以更改 href

javascript - Node.js - 如何以正确的方式链接 Promise

javascript - 如何在 react-select 的选项中添加图标?

javascript - 刷新后将轮播保持在同一张幻灯片上

php - 正确处理 php 中转义的 unicode 字符