Javascript jQuery在悬停时交换图像,然后将其替换为原始的打开悬停关闭

Javascript jQuery在悬停时交换图像,然后将其替换为原始的打开悬停关闭,javascript,jquery,html,Javascript,Jquery,Html,我使用下面的代码在孩子的父母悬停时交换一个图像src。如何将原始源保存在变量中,并在悬停关闭时将图像返回到其原始源 $("#parent span").hover(function(){ var currentImage = $('img', this ).attr("src","images/orbs/yellowBar.png"); $('img', this ).attr("src","images/yellowBar.png");

我使用下面的代码在孩子的父母悬停时交换一个图像src。如何将原始源保存在变量中,并在悬停关闭时将图像返回到其原始源

      $("#parent span").hover(function(){
          var currentImage = $('img', this ).attr("src","images/orbs/yellowBar.png");
          $('img', this ).attr("src","images/yellowBar.png");


        },function(){

          $('img', this ).attr("src",currentImage);

      });

在功能之外定义
currentImage

var currentImage;

$("#parent span").hover(function() {
    currentImage = $('img', this).attr("src", "images/orbs/yellowBar.png");
    $('img', this).attr("src", "images/yellowBar.png");
}, function() {
    $('img', this).attr("src", currentImage);
});

我会在原始源的元素上使用并设置一个数据点,然后在鼠标移出时检索它。

我建议使用mouseenter、mouseleave,如下所示:

var currentImage;
$("#parent span").mouseenter(function(){
    currentImage = $('img', this ).attr("src");
    $('img', this ).attr("src","images/yellowBar.png");
}).mouseleave(function(){
    $('img', this ).attr("src", currentImage);
});

如果这不起作用,请提供您的HTML代码。

对于我来说,更好的方法是创建两个具有不同背景图像的css类,并且根本不使用javascript/jquery切换悬停图像

css:

html:


基于Dylan Watt的建议,我将使用
.data()
来避免全局变量

比如说:

$("span").mouseenter(function () {
    var currentImage = $('img', this).attr("src");
    $('img', this).data("orig", currentImage)
    .attr("src", "http://placehold.it/350x150&text=hover");
}).mouseleave(function () {
    var original = $('img', this).data("orig");
    $('img', this).attr("src", original);
});
这是一把小提琴,你可以根据自己的使用进行调整:


尝试将其保存到全局变量。所以,在这个函数之外。由于全局变量的存在,非常容易出错。此外,它也是不正确的,因为在本例中,
currentImage
是一个对象。我同意@dfsq,全局变量似乎不是本例中的最佳选项,因为如上所述,它可能会意外被覆盖。虽然我也同意,重要的是展示最基本的示例来表达解决问题的原则。这实际上是应该如何正确完成的,不知道为什么会被否决。可以通过减少DOM查询来改进。您可以链接jQuery调用并避免多次重新选择
$('img',this)
<div class="time-stamp-img"></div>
$("span").mouseenter(function () {
    var currentImage = $('img', this).attr("src");
    $('img', this).data("orig", currentImage)
    .attr("src", "http://placehold.it/350x150&text=hover");
}).mouseleave(function () {
    var original = $('img', this).data("orig");
    $('img', this).attr("src", original);
});