gpt4 book ai didi

javascript - 如何使用javascript从多个div中只选择一个DIV

转载 作者:太空宇宙 更新时间:2023-11-03 19:57:36 25 4
gpt4 key购买 nike

我的 HTML 中有以下代码,其中有多个 DIV,我想使用这些 DIV 作为选项。出于这个原因,被点击的 DIV 应该是可选的(其他未选中 - 只有一个应该是事件的)并且当我点击确认链接时,所选 DIV 中的值应该显示在消息框中。

<div style="margin-top:10px;">
<div class="optionsecoptions">
&nbsp;&nbsp;Computers
</div>
<div class="optionsecoptions" style="top:151px;">
&nbsp;&nbsp;Electronics
</div>
<div class="optionsecoptions" style="top:212px;">
&nbsp;&nbsp;Mechanical
</div>
<div class="optionsecoptions" style="top:273px;">
&nbsp;&nbsp;Electrical
</div>
</div>
<a href="#"> Confirm </a>

这是演示:

http://jsfiddle.net/sathish_opr/ntxuc69a/

我在 Jquery 中尝试了一些解决方案,但这是否可能使用简单的 javascript?请帮忙!

最佳答案

您可以使用 addEventListener用于从 <div> 添加/删除特定类的仅 javascript 解决方案.

您需要遍历类为 .optionsecoptions 的所有元素并在它们中的每一个上附加点击事件监听器,(或者更好地将所有 <div> 封装在包装器中并利用点击事件的冒泡)

var x = document.getElementsByClassName('optionsecoptions')
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function(){

var selectedEl = document.querySelector(".selected");
if(selectedEl){
selectedEl.classList.remove("selected");
}
this.classList.add("selected");

}, false);;
}

这是工作 demo

关于javascript - 如何使用javascript从多个div中只选择一个DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31531461/

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