简体   繁体   中英

to image click I gave a function, on clicking it am getting image id, using this I have to change the image using javascript

I gave a function, on clicking it am getting image id, using this I have to change the image using javascript.

The code is as follows

$('img').live('click', function () {
     alert(this.id);
 });

the outputs are as follows like_0,like_1...... and unlike_0,unlike_1.........

But depending on the output I have to change image

$("#like_").click(function () {
    $("#tipid").val(1);
    $("#like_").attr("src", "images/ic_like_select.png");
    $("#unlike_").attr("src", "images/ic_unlike_unselect.png");
});
$("#unlike_").click(function () {
    $("#tipid").val(0);
    $("#like_").attr("src", "images/ic_like_unselect.png");
    $("#unlike_").attr("src", "images/ic_unlike_select.png");
});

My problem is I was not known how to change. Can someone help me thanks.

you could take a look at the toggle function from jquery

x.toggle(function(){}, function(){})

something similar has been done here !

If I understand well, you want to change your image, and you have to change it depending on the id.

I'll explain what I'd try in your place:

Let's supose this is the picture I want to change:

<img id='like_0' src='/path/to/image' />

So, once you have the id of this image (like_0) you could try this in your javascript function:

document.getElementById("like_0").src="../path/new_img.png";

This last instruction changes the path of the image to the new one

fiddle demo

like_img="like_url";
unlike_img="unlike_url";

toggle=function(){
    if($(this).attr("id").match(/^like_/)!=null)
    {
        if($("#tipid").val()==0)
        {
            $("#tipid").val(1);
            $("[id^=like_]").attr('src', unlike_img);
            $("[id^=unlike_]").attr('src', like_img);
        }
        else
        {
            $("#tipid").val(0);
            $("[id^=like_]").attr('src', like_img);
            $("[id^=unlike_]").attr('src', unlike_img);        
        }
    }
    if($(this).attr("id").match(/^unlike_/)!=null)
    {
        if($("#tipid").val()==1)
        {
            $("#tipid").val(0);
            $("[id^=unlike_]").attr('src', like_img);
            $("[id^=like_]").attr('src', unlike_img);
        }
        else
        {
            $("#tipid").val(1);
            $("[id^=unlike_]").attr('src', unlike_img);
            $("[id^=like_]").attr('src', like_img);        
        }
    }
}

$('img').on('click', toggle);

Your question seemed not clear enough. Still I think the demo may help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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