猿问

如何按类名正确定位?

我正在尝试在 JS 上练习一些东西,我想在点击时切换多个 div 以更改它们的颜色,但我似乎无法正确定位第一个。当我按标签名称执行此操作时很好,但按类它似乎不起作用。我究竟做错了什么?谢谢!


编辑。这是您更正后我的代码的样子。


<body>

    <div class="container">


        <div class="one">


        </div>

        <div class="two">


        </div>

        <div class="three">


        </div>

        <div class="four">


        </div>


    </div>


    <script src="script.js"></script>

</body>


let boxOne = document.getElementsByClassName("one")[0]


boxOne.onclick = function() {

    alert("Clicked!")

}


互换的青春
浏览 108回答 4
4回答

智慧大石

我要补充一点,如果选择器仅由一个元素使用,最好分配一个 id 并使用 getElementById。let boxOne = document.getElementById("one");let allBoxes = document.getElementsByClassName("square");boxOne.onclick = function() {&nbsp; alert("Clicked via ID");}const arr = [1, 2, 3];arr.forEach(i => {&nbsp; allBoxes[i].onclick = function() {&nbsp; &nbsp; alert("Clicked via Class");&nbsp; }}).square {&nbsp; width: 100px;&nbsp; height: 100px;&nbsp; background: blue;&nbsp; margin: 20px;&nbsp; font-size: 50px;&nbsp; color: white;&nbsp; text-align: center;&nbsp; display: flex;&nbsp; flex-direction: column;&nbsp; justify-content: center;&nbsp; cursor: pointer;}<body>&nbsp; <div class="container">&nbsp; &nbsp; <div class="square" id="one">&nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="square" id="two">&nbsp; &nbsp; &nbsp; 2&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="square" id="three">&nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="square" id="four">&nbsp; &nbsp; &nbsp; 4&nbsp; &nbsp; </div>&nbsp; </div></body>

PIPIONE

文档。getElementsByClassName 返回具有该类名的元素数组(不带点)querySelector 用于 css 选择器(例如“.one”、“div.one”)querySelectorAll 像 2. 但返回数组

料青山看我应如是

let boxOne = document.getElementsByClassName("one")[0]boxOne.onclick = function() {&nbsp; &nbsp; alert("Clicked!")}div {&nbsp; width: 100px;&nbsp; height: 100px;&nbsp; margin: 30px;&nbsp; background: blue}<body>&nbsp; &nbsp; <div class="container">&nbsp; &nbsp; &nbsp; &nbsp; <div class="one">&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="two">&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="three">&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="four">&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; &nbsp; <script src="script.js"></script></body>

扬帆大鱼

使用此行:document.getElementsByClassName(".one")[0]&nbsp;您已经针对 div,因此将其更改&nbsp;boxOne[0].onclick =&nbsp;为:&nbsp;boxOne.onclick =
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答