简体   繁体   中英

changing id back and forth in one function

This is a part of a flip coin kinda page i made the animation for the coin on css depending on the current state and the future state of the coin so with every run of the function i have to reset the coin back to the default state and then set it to the future state with the new css animation the thing is.. when i ran the code it didn't work until i added the alert("hi") line.. i have no idea why and i want to fix this because i don't want the user to click ok everytime he needs to flip the coin

var flipCoin = function () {
flips ++;
var result = 1;
if (document.getElementById("fromHeadsToHeads") !== null) {
document.getElementById("fromHeadsToHeads").id = "defaultHeads";
}

switch (result) {
    case 1 :

        if (document.getElementById("defaultHeads") !== null) {
            alert("hi")
            document.getElementById("numFlips").innerHTML = flips;
            document.getElementById("defaultHeads").id = "fromHeadsToHeads";
        }
    break;
}

The problem is likely that the browser has not re rendered the DOM yet between you setting the I'd and you calling getElementById.

When you alert something the browser probably triggers a render.

There are likely much better ways of going about what you are trying to do, but to address the immediate problem of the DOM not being re rendered, you could put everything following the alert in a new anonymous function that is called by a setTimeout. Sort of like:

SetTimeout (function() {...},100). You will have to get the variable scoping right, but this should give the DOM a chance to be updated.

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