简体   繁体   中英

Jquery stop the first clicked button from executing the same code

My issue seems like it would be on here already but I just can't find it. Apologies in advance!!!!

After clicking one of multiple (unique) buttons, the initial corresponding div selected keeps executing even when clicking a different button.

How can I stop the first clicked button from executing the same code?

HTML

<button id="freeButton" type="button">Redeem</button>
<button id="giftCardButton" type="button">Redeem</button>

Jquery

content[0] = content;
content[1] = other content;

$(freeButton).click(function(){
    if(!visible) {
        $('#items').append(content[0]);
            visible = true;
    } else {
        $('#items').remove(content[0]);
            visible = false;
    }
});

$(giftCardButton).click(function(){
    if(!visible) {
        $('#items').append(content[1]);
            visible = true;
    } else {
        $('#items').remove(content[1]);
            visible = false;
    }
});

With this line $('#items').remove(content[1]); you are removing the element from the dom and with append you are not replacing the content of the div, you're just adding to it.

you need to use the html() methode instead.

 var content = ["content", "other content"]; visible = false; $('#freeButton').click(function(){ if(!visible) { $('#items').html(content[0]); visible = true; } else { $('#items').html(""); visible = false; } }); $('#giftCardButton').click(function(){ if(!visible) { $('#items').html(content[1]); visible = true; } else { $('#items').html(""); visible = false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="freeButton" type="button">Redeem1</button> <button id="giftCardButton" type="button">Redeem2</button> <div id="items"></div> 

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