简体   繁体   中英

Checking to make sure the same item can't be clicked twice in a row with jQuery / jScript

So, I have a script I've been working on it can be seen here: http://xeo.tryptamine.tv/lookbook2/ Now if you play around with that script you will see if you click the image it's already on it still gets that fade effect. I need to know how to properly unbind the event and rebind it after another one is clicked. Here is the click function for it:

            $('.righticons img').click(function(){
            var z = $(this).attr("class");
            $('.main a img:eq('+z+')').hide();
            $('.main a img:eq('+z+')').css({"z-index": y});
            $('.main a img:eq('+z+')').fadeIn();
            y++;

I have tried to make an if statement something like this, but last came up undefined.

            $('.righticons img').click(function(){
            var z = $(this).attr("class");
            if (z != last){
            var last = z;
            $('.main a img:eq('+z+')').hide();
            $('.main a img:eq('+z+')').css({"z-index": y});
            $('.main a img:eq('+z+')').fadeIn();
            y++;
            };

I even started toying around with .unbind('click') but have no clue how to bind it back. PS, I have the script generating a number for each thumb on the side and appending it to the class attribute according to it's array position. Thanks for any answers!

There are several ways to handle this, but you can avoid binding and rebinding if you just track if this item was the last one selected:

$('.righticons img').click(function(){
    if ($(this).data('selected') !== true) {
        var z = $(this).attr("class");

        $('.main a img:eq('+z+')').hide();
        $('.main a img:eq('+z+')').css({"z-index": y});
        $('.main a img:eq('+z+')').fadeIn();

        y++;

        $(this).data('selected', true);
    }
});
$('.righticons img').click(function(){
    if ($(this).data('selected') !== true) {
        var z = $(this).attr("class");

        $('.main a img:eq('+z+')').hide();
        $('.main a img:eq('+z+')').css({"z-index": y});
        $('.main a img:eq('+z+')').fadeIn();
        $('.righticons img').data('selected', false)
        $(this).data('selected', true);
        y++; 
    }
});

appending false to all but $(this)

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