简体   繁体   English

JQuery - 点击一个div内的图像?

[英]JQuery - Toggle an image inside of a div on click?

So I have a toggled div with an image inside of it that toggles the scrolling of the next div: 所以我有一个切换的div,里面有一个图像,切换下一个div的滚动:

<div class="section">
<img src="on.png"> Stuff </div>
<div class="under" style="height:302px;"> Hi </div>

Here's the JQuery for it: 这是它的JQuery:

$(".section").click(function(){
    $(this).next('div').slideToggle(1200);
});

How would I make it so on the click function for my div, it toggles the image to "off.png"? 我如何在我的div的click功能上做到这一点,它将图像切换为“off.png”? And if the src is "off.png", it toggles to "on.png"? 如果src是“off.png”,它会切换到“on.png”? Thanks. 谢谢。 (Sorry I'm still a noob at JQuery) (对不起,我还是JQuery的菜鸟)

$(function(){ 
    $(".section").click(function(){ 
   $("img").attr('src',  
                ($("img").attr('src') == 'http://www3.picturepush.com/photo/a/2772891/64c/png/power-off.png?v0'  
                    ? 'http://kiwianon.com/forums/Themes/Simple_Green/images/on.png'  
                    : 'http://www3.picturepush.com/photo/a/2772891/64c/png/power-off.png?v0' 
                     ) 
                )  
    }); 
}); 

demo 演示

$(".section").click(function(){

    var img = $(this).find("img").eq(0); //add an Id to your img tag so you can refine this selector. 
    if(img.attr("src") == "on.png")
    {
        img.attr("src","off.png");
    }
    else{
        img.attr("src","on.png");
    }

    $(this).next('div').slideToggle(1200);
});

Ken, this is very simple! 肯,这很简单! Just use the code below: 只需使用以下代码:

$('.section').click(function(){
var currentimg=$(this).find('img').attr('src');
if(currentimg=="off.png"){
$(this).find('img').attr('src','on.png');
}
else{
$(this).find('img').attr('src','off.png');
}
});

Use $(selector).attr("src", "theImageFilePath") to change the image. 使用$(selector).attr("src", "theImageFilePath")来更改图像。

The state could be represented in several ways, including global/module variable, $(selector).data(...), or simply by checking the current value of the "src" attribute. 状态可以用几种方式表示,包括全局/模块变量,$(选择器).data(...),或者只是通过检查“src”属性的当前值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM