gpt4 book ai didi

javascript - 为数组中的按钮指定一个自己的 ID

转载 作者:行者123 更新时间:2023-12-03 11:37:26 25 4
gpt4 key购买 nike

我正在为学校做的一个项目需要帮助。我们需要为电影院制作一个预订系统。为了生成椅子,我创建了一个数组,但如何为每个按钮提供一个自己的 ID?

这是我的代码:

function chair(){    
for( i = 1 ; i <= 10; i = i + 1 ){
if ( i > 3 && i < 8 ){
document.write("<button>button</button>");
}else{
document.write("<button>hi</button>");
}
}
}

最佳答案

好吧,你可以这样做:

document.write("<button id=btn" + i + ">button</button>");
<小时/>

旁注:

  1. 您正在成为 The Horror of Implicit Globals 的牺牲品— 声明您的i变量。

  2. 通常,除非有理由做其他事情,在编程中我们从 0 开始。而不是1 :

    for (i = 0; i < 10; i = i + 1)

    您不必这样做,但这是正常的事情。

  3. i = i + 1可以写成++i (“增量i”):

    for (i = 0; i < 10; ++i)

    同样,你不必这样做,但是它(或其表兄弟 i++ )比 i = i + 1 更常见。 .

  4. document.write对于小类作业等来说很好,但只是FWIW,你可能不想在现实世界中使用它。使用DOM相反:

    var btn = document.createElement("button");
    btn.id = "btn" + i;
    document.body.appendChild(btn);

HTH,当你正在学习时......

关于javascript - 为数组中的按钮指定一个自己的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425170/

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