如何使用HTML / JavaScript中的getElementsByClassName方法将单个功能应用于所有按钮?

问题描述 投票:0回答:1

我的目标是创建一个表格,其中每个单元格都包含一个按钮,单击该按钮可以更改颜色。我使用了只能在一个按钮上使用的getElementById方法,因为我只能使用一次Ids。我也尝试过使用getElementsByClass,以便该函数将应用于具有该类名称的所有按钮,但是由于某种原因,这也不起作用。

我缺少什么吗?

<div class = box_2>
    <table class = "calendar">
        <tr>
            <th> </th>
            <th>J</th>
            <th>F</th>
            <th>M</th>
            <th>A</th>
        </tr>
        <tr>
            <td>1</td>
            <td><button class = "changecolor">  </button></td>
            <td><button class = "changecolor">  </button></td>
            <td><button class = "changecolor">  </button></td>
            <td><button class = "changecolor">  </button></td>
        </tr>
        <tr>
            <td>2</td>
            <td><button class = "changecolor">  </button></td>
            <td><button class = "changecolor">  </button></td>
            <td><button class = "changecolor">  </button></td>
            <td><button class = "changecolor">  </button></td>
         </tr>
    </table>
</div>

</div>
    <script type="text/javascript">
    const changecolor = document.getElementsByClassName('changecolor');
    colors = ["#ff57a5", "#e7c9a2dc", "#b2e075", "#84add3", "#5e5d64", "#ff7a22", "#7b57df"];
        let colorindex = 0;
        changecolor.addEventListener('click', change()=> {
            document.getElementsByClassName('changecolor').style.background = colors[colorindex];
            colorindex = (++colorindex) % colors.length;
        });
    </script>



THE CODE BELOW WORKS FOR ONLY ONE BUTTON USING THE getElementById METHOD

    <script type="text/javascript">
    const changecolor = document.getElementById('changecolor');
    colors = ["#ff57a5", "#e7c9a2dc", "#b2e075", "#84add3", "#5e5d64", "#ff7a22", "#7b57df"];
        let colorindex = 0;
        changecolor.addEventListener('click', ()=> {
            document.getElementById('changecolor').style.background = colors[colorindex];
            colorindex = (++colorindex) % colors.length;
        });
    </script>

javascript html getelementsbyclassname
1个回答
0
投票

我没有足够的声誉,所以我无法发表评论。

问题是getElementsByClassName返回一个数组,而getElementById返回单个元素。

您将需要遍历getElementsByClassName返回的所有元素,并将事件侦听器添加到每个元素中。

© www.soinside.com 2019 - 2024. All rights reserved.