gpt4 book ai didi

JavaScript,如何根据变量更改id?

转载 作者:行者123 更新时间:2023-11-28 03:44:55 25 4
gpt4 key购买 nike

基本上,我正在使用 JavaScript 测试 Arduino 的代码。我想要做的(在Arduino上)是单击按钮(+)来更改屏幕(有8个屏幕,0个索引)。实际发生的情况是,您单击按钮,这会增加一个变量,然后该变量控制“激活”哪个屏幕。当变量等于 7 时,下一次按将其更改为 0。还有一个 (-) 按钮,其作用相反。

以上是我想在我的Arduino LCD上实现的目标。但是,我用 JavaScript 编写它只是为了测试逻辑等。

这是我当前的代码:

<p id='cool'></p>
<button id='plus' onclick='plus(); check()'>+</button>
<button id='sub' onclick='sub(); check()'>-</button>
<br>
<p id='show'></p>

<script>

var cool = document.getElementById('cool');
var status = 0;

function plus(){

if(status == 7){
status = 0;
}else{
status++;
}

cool.innerHTML = status;
}

function sub(){

if(status == 0){
status = 7;
}else{
status--;
}

cool.innerHTML = status;
}

</script>

cool id 仅显示状态。

我想根据状态的值更改显示 ID 的内容。我最初想使用 switch 语句,例如:

function check(){
switch(status){
case 0:
document.getElementById('show') = "one";
break;
case 1:
document.getElementById('show') = "two";
break;
default:
document.getElementById('show') = "default";
}
}

您会注意到 check() 函数已位于按钮的 onclick 中。

不幸的是,这个方法对我不起作用,有什么想法吗?

最佳答案

document.getElementById('show').innerHTML="one"似乎就是你想要的 –

或者也许

document.getElementById('show').innerHTML=["zero","one","two",...,"seven"][status]

这是一个完整的示例 - 请注意,该代码片段将所有这些内容包装在“window.onload”类型的事件处理程序中。您需要将脚本放在 </body> 之前在没有 onload 的情况下获得相同的效果

var screens = [
"Screen 1",
"Screen 2",
"Screen 3",
"Screen 4",
"Screen 5",
"Screen 6",
"Screen 7",
"Screen 8"
];

var cool = document.getElementById('cool');
var show = document.getElementById('show');
var status = 0;

function plus() {

if (status == 7) {
status = 0;
} else {
status++;
}

cool.innerHTML = status;
}

function sub() {

if (status == 0) {
status = 7;
} else {
status--;
}
}
function check() {
cool.innerHTML = status;
show.innerHTML = screens[status];
}
check(); // show the first screen (status = 0)
<p id='cool'></p>
<button id='plus' onclick='plus(); check()'>+</button>
<button id='sub' onclick='sub(); check()'>-</button>
<br>
<p id='show'></p>

关于JavaScript,如何根据变量更改id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48586301/

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