簡體   English   中英

如何將參數傳遞給“ setTimeout”函數?

[英]How do I pass arguments to a 'setTimeout' function?

如何使這些函數將變量用作ID? 我不能使用setTimeout正常工作。

    <script type="text/javascript">
        function changeBarAWidth() {
            var bar = document.getElementById('firstbar');
            bar.style.width = lengthA + "px";
        }

        function increaseBarA() {
            if (lengthA < fullBarA) {
                changeBarAWidth();
                lengthA = (lengthA + 2);
                setTimeout("increaseBarA()", 10);  // <-- How do I pass "firstbar"?
           }
        }

        function resetLengthA() {
            lengthA = 0;
            changeBarAWidth();
        }

        var barA = 'firstbar';
        var percentA = 80;
        var fullBarA = (percentA * 2);
        var lengthA = 0;
    </script>
    <style type="text/css">
        ul {
            list-style-type: none;
        }
        .bar {
            width: 50px;
            height: 5px;
            background-color: red;
        }
        .back {
            background-color: black;
            height: 5px;
            width: 200px;
        }
    </style>
</head>
<body onload="increaseBarA()">
    <ul>
        <li class="back">
            <p class="bar" id="firstbar"></p>
        </li>
    </ul>
    <button onClick="increaseBarA()">Test Change</button>
    <button onClick="resetLengthA()">Reset</button>

我不得不使用setTimeout(function() { YourFuncwith(params); }, 10);

這是腳本。 如果有人想復制,請執行以下操作:

 // functions to show poll reults, div width increase every tenth of a second, // looks like poll is sliding. // length is name of global length variable you declare, mine are at bottom of script // I will use php to dynaimcally give variable values based on poll results. function changeBarWidth(id, length) { var bar = document.getElementById(id); bar.style.width = length + "px"; } /* max is how long you want the poll to slide to, my background is 200px * so I set to (percent*2); */ function increaseBar(id, max, length) { var full = max; if (length < full) { changeBarWidth(id, length); length = (length + 2); setTimeout(function() { increaseBar(id, max, length); }, 10); } } var barA = 'firstbar'; var percentA = 80; var fullBarA = (percentA * 2); var lengthA = 0; var lengthB = 0; 
 ul { list-style-type: none; } .bar { width: 50px; height: 5px; background-color: red; } .back { background-color: black; height: 5px; width: 200px; } 
 <body onload="increaseBar(barA, percentA, lengthA)"> <div id="pollresults"> <ul> <li class="back"> <p class="bar" id="firstbar"></p> </li> <li class="back"> <p class="bar" id="secondbar"></p> </li> </ul> </div> <button onClick="increaseBar('secondbar',fullBarA,lengthB)">Test Change</button> </body> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM