我需要使用 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/