JavaScript onclick requires two clicks

前端 未结 8 1066
执笔经年
执笔经年 2021-01-14 19:33

My problem is that when onclicktriggers the toggleNew function it\'s not executing but when I click the div a second time it\'s execut

相关标签:
8条回答
  • 2021-01-14 20:23

    You need to call the function like onclick="toggleNew();" in the div onclick. I just added your code in fiddle.

    0 讨论(0)
  • 2021-01-14 20:27

    I had the same double click required issue. I was using an internal style sheet which was correctly setting the display like this. When loading the HTML file #YourID was not visible as expected.

    #YourID {
        display: none;
    }
    

    When clicking the button tied to the function I noticed that the first click set the inline display to style="display: none;". The second click set the inline style="display: block;" and of course then it displayed as expected.

    I found that I needed to set the element directly inline with style="display: none;" and just removed the intern style sheet entry (Above "#YourID").

    I'm doubtful that this is 100% the correct answer in every scenario but it would seem the underlying issue is caused by the element not being set in the appropriate initial state for the function to act on it properly.

    https://jsfiddle.net/em05a1kf

    <div id="YourID" style="display: none;">
    <b>Super Hidden Content</b>
    </div>
    
    <button onclick="ToggleID('YourID');">Do Foo</button>
    
    <script type="text/javascript">
    function ToggleID(idname) {
        var x = document.getElementById(idname);
        (x.style.display === "none") ? (x.style.display = "block") : (x.style.display = "none");
        return false;
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题