簡體   English   中英

F# 中的 Javascript onclick 替代方案 - 安全

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM