[英]Javascript onclick alternative in F# - SAFE
我在一个页面上有两个大小匹配的 div,我想隐藏一个并显示另一个,单击按钮在它们之间交换。 通常我会使用 javascript click 事件来切换显示,但我不确定如何在 SAFE 中使用默认 Javascript,并且想知道是否有 F# 替代方案。
我想要与此类似的结果(但在 F# 中):
var divs = document.getElementsByClassName("square"); var inactive = document.getElementsByClassName("square inactive"); function swapDivsOnClick(div) { active = document.getElementById(div); inactive[0].classList.remove("inactive"); active.classList.add("inactive"); }
.square { width: 150px; height: 150px; } #red { background-color: red; } #green { background-color: green; } .inactive { display: none; } h1 { color: white; }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/styles.css"> <title>Page Title</title> </head> <body> <div id="red" class="square"> <button class="toggle" onclick="swapDivsOnClick('red')">Click Me</button> <h1>Div 1</h1> </div> <div id="green" class="square inactive"> <button class="toggle" onclick="swapDivsOnClick('green')">Click Me</button> <h1>Div 2</h1> </div> </body> <script src="js/scripts.js"></script> </html>
你不需要onclick="swapDivsOnClick('red')"
尝试使用它
var divs = document.getElementsByClassName("square");
if(divs.length) {
for (let el of divs) {
el.addEventListener("click", function(e) {
// here you can remove "inactive" class from all elements
for (let elem of divs) {
elem.classList.remove("inactive");
}
// and the add "inactive" class to current clicked element
this.classList.add("inactive");
})
}
}
它将从所有 div 中删除“非活动”类,然后将该类添加到当前单击的 div。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.