search

Home  >  Q&A  >  body text

The innerHTML of the button cannot be displayed on the screen

So I have a problem with innerHTML. I have an empty array buttons and I fill it using a for loop. Then I use another for loop to set each button's innerHTML to "Info", but when I check my site, the buttons are still empty.

//数组
                let buttons = [];

                //循环问题
                for(let i = 0; i < 2; i++)
                {
                    //填充按钮数组的循环
                    for(let l = 0; l < 4; l++)
                {
                    buttons[l] = $(`#btn${l}`);
                } 

                //循环设置按钮的innerHTML
                for(let s = 0; s < buttons.length; s++)
                {
                    buttons[s].innerHTML = "Info";
                }


                }


            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Quiz Game</title>
            </head>
            <body>
            <!-- 主容器 -->
                <div class="main-container">
                    <!-- 头部 -->
                    <h1 class="header" id="header">Quiz Game</h1>

                    <!-- 按钮 -->
                    <button id="btn0"></button>

                    <button id="btn1"></button>

                    <button id="btn2"></button>

                    <button id="btn3"></button>
                </div>


            <script src="/library/jquery-3.6.3.min.js"></script>
            <script src="test1.js"></script>
            </body>
            </html>
P粉024986150P粉024986150442 days ago505

reply all(1)I'll reply

  • P粉667649253

    P粉6676492532023-09-11 00:06:53

    Using jQuery, you should call buttons[s].html("Info"); to set innerHTML. However, using buttons[s].text("Info"); is better here because there aren't actually any HTML tags in the string.

    You can also use a selector to select all buttons starting with "btn" and set their text all at once.

    const buttons = $('[id^=btn]');
    buttons.text('Info');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="btn0"></button>
    <button id="btn1"></button>
    <button id="btn2"></button>
    <button id="btn3"></button>

    reply
    0
  • Cancelreply