gpt4 book ai didi

javascript - 如何将参数传递给 'setTimeout' 函数?

转载 作者:行者123 更新时间:2023-11-28 15:01:20 25 4
gpt4 key购买 nike

如何让这些函数使用变量作为 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>

关于javascript - 如何将参数传递给 'setTimeout' 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1957509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com