2017-05-04 55 views
0

我其实知道如何用Jquery更改图像,但以下案例让我真的陷入困境。 所以我有一个div我显示图像点击这样的:更改图像与jQuery使用.toggle()在相同的功能

$(dcoument).ready(function() { 
    $('.image').click(function() { 
     $('.element').toggle(); 
     $(this).attr('src', 'image2.png'); 
    }); 
}; 

Someow .attr()功能不会在这种情况下工作,我不知道为什么,我甚至有一个函数改变这个特定的像这样悬停的图像:

$(document).ready(function() { 
    $('.image').hover(function() { 
     $(this).attr('src', 'image2.png'); 
    }, function() { 
     $(this).attr('src', 'image1.png'); 
    }); 
} 

它工作的方式应该如此。任何想法为什么我发布的代码不能改变点击图像?提前致谢。

+1

你拼错'document'在'$(dcoument)。就绪(函数(){' –

回答

0

您可以使用hasClass添加条件。

<img src="image1.png"> 
<button>change</button> 

$(function(){ 
    $('button').on('click', function(){ 
    if($('img').hasClass('fb')) { 
     $('img').removeClass('fb'); 
     $('img').attr('src', 'http://townandcountryremovals.com/wp-content/uploads/2013/10/firefox-logo-200x200.png'); 
    } else { 
     $('img').addClass('fb'); 
     $('img').attr('src', 'http://www.thebloodycure.com/wp-content/uploads/2016/02/FaceBook-Logo-200x200.png'); 
    } 
    }); 
}) 

https://jsfiddle.net/c84kouny/1/

+0

这是正确的答案,谢谢你投资你的时间,我的问题的解决,我能找到一个问题,这是因为我之前的悬停功能,我在课堂上玩弄了很多东西,并且让它工作起来, –

+0

太好了,你可以编写任何你喜欢的东西。 –