在悬停在另一个 div 上时更改主 div 的 src

changing src of a main div on hovering on another divs

<html>
<head><script src="jquery-1.10.1.min.js"></script></head>
<body>
<div><img src="images/img-40.jpg" class="Main-image"/></div>

<div id="iranimg"><img src="images/irani.jpg" style="display:none;"/>Iran </div>
<div id="spainimg"><img src="images/spanin.jpg" style="display:none;"/>Spain </div>
<div id="turkeyimg"><img src="images/turkey.jpg" style="display:none;"/>Turkey </div>



<script>

$(document).ready(function(){
$('#iranimg').hover(function() {
$( '.Main-image' ).attr("src","images/irani.jpg");
}, function() {
    $( '.Main-image' ).attr("src","images/img-40.jpg");

});


})
</script>

</body>
</html>

我想更改另一个 div 的 src of 'main-image' div with asrc,只有当悬停在另一个 div 上时。

当我将鼠标悬停在 div 上时,它会替换为特定的 src

我想动态获取每个 div 的 src 并将其替换为主 div 图像的 src

悬停时获取内部 img 标签的 src 并替换为

$('#iranimg,#spainimg,#turkeyimg').hover(function() {
  $('.Main-image').attr("src", $('img',this).attr('src'));
}, function() {
  $('.Main-image').attr("src", "images/img-40.jpg");
});

仅供参考: 使用 class 而不是 id,这样可以使它更简单

jQuery:

$('.imgChange').hover(function() {
  $('.Main-image').attr("src", $('img',this).attr('src'));
}, function() {
  $('.Main-image').attr("src", "images/img-40.jpg");
});

HTML:

<div><img src="images/img-40.jpg" class="Main-image"/></div>

<div class="imgChange"><img src="images/irani.jpg" style="display:none;"/>Iran </div>
<div class="imgChange"><img src="images/spanin.jpg" style="display:none;"/>Spain </div>
<div class="imgChange"><img src="images/turkey.jpg" style="display:none;"/>Turkey </div>
 $('#iranimg').hover(function() {
    $('.Main-image').attr('src', $(this).find('img').attr('src'));
 }, function() {
    $('.Main-image').attr('src', "images/img-40.jpg");
 });

尝试:

   $('div[id$="img"]').hover(function() {
    $( '.Main-image' ).attr("src",$(this).find('img').attr('src'));
    }, function() {
    $( '.Main-image' ).attr("src","images/img-40.jpg");

    });

你的意思是:

如果预加载图像,您可以保留图像,但使用数据属性和 class 将事件添加到所有 div

$(function() {
  $('.countries').hover(function() {
    $('.Main-image').attr("src", $(this).data("src"));
  }, function() {
    $('.Main-image').attr("src", "images/img-40.jpg");
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <img src="images/img-40.jpg" class="Main-image" />
</div>

<div class="countries" id="iranimg" data-src="images/irani.jpg">Iran</div>
<div class="countries" id="spainimg" data-src="images/spanin.jpg">Spain</div>
<div class="countries" id="turkeyimg" data-src="images/turkey.jpg">Turkey</div>