尝试再次点击和返回更改图像

我试图在单击一个类时切换图像。 到目前为止我有这个(下面)并且它可以将我的’plus.png’改为我的’minus.png’,但如果再次点击该类,我需要将它改回我的’plus.png’。

我有以下jQuery:

 $(document).ready(function () { $('label.tree-toggler, .yellow').click(function () { $(this).parent().children('.yellow').attr('src', 'img/minus.png'); }); });  

HTML

 

  • 有人可以通过添加我所拥有的东西来帮助我,我将非常感激!

    您可以添加/删除类以跟踪您正在使用的src图像。 像这样的东西:

     $('label.tree-toggler, .yellow').click(function () { if ( $(this).parent().children('.yellow').hasClass('minus') ) { $(this).parent().children('.yellow').attr('src', 'https://stackoverflow.com/questions/24811672/trying-to-change-an-image-on-click-and-back-again/img/plus.png').removeClass('minus'); } else { $(this).parent().children('.yellow').attr('src', 'img/minus.png').addClass('minus'); } }); 

    您还可以使用数据属性并执行类似操作:

     $('label.tree-toggler, .yellow').click(function () { if ( $(this).parent().children('.yellow').data('current_src') == 'minus') { $(this).parent().children('.yellow').attr('src', 'https://stackoverflow.com/questions/24811672/trying-to-change-an-image-on-click-and-back-again/img/plus.png').data('current_src', 'plus'); } else { $(this).parent().children('.yellow').attr('src', 'img/minus.png').data('current_src', 'minus'); } }); 

    使用data属性需要在元素上初始设置data-current_src='minus'

    我将这样做的方式是……

     $(document).ready( function() { $(".className").click( var imgPath = $("img").attr('src'); if(imgPath === "+.png") { // check against current path // change the path to - } else { // change the path to + } 

    ); });

    我没有测试它,但那是个主意

    我建议在切换图像时通过JQuery添加另一个类,如.active.shown 。 这样你就可以检查你正在查询的对象的当前状态。

    Jquery可能看起来像

     $('label.tree-toggler, .yellow').click(function () { // If the active class is NOT applied if( !( $(this).parent().children('.yellow').hasClass('active') ) ) { // Apply it and change the image $(this).parent().children('.yellow').addClass('active').attr('src','img/minus.png'); } else $(this).parent().children('.yellow').removeClass('active').attr('src', 'https://stackoverflow.com/questions/24811672/trying-to-change-an-image-on-click-and-back-again/img/plus.png'); }); 

    这里发生的是active类用于确定显示的图像的状态。 单击它时,您将更改图像并应用标记。

    每次单击后,都会检查标志并执行相应的操作。 希望有所帮助! 我还是新来的SO =。=“

    如果你想用JS做,我建议你把:

    • 您在src的初始图像
    • data-alternative替代图像

    像这样 :

     

  • 和JS:

      

    你看到了Jquery的切换function吗?

    http://api.jquery.com/toggle/