簡體   English   中英

JavaScript 切換按鈕不更改按鈕 state

[英]JavaScript toggle button not changing button state

我有一個按鈕,單擊該按鈕時,我希望文本從ON變為OFF (切換)。 但是,我似乎無法讓 JavaScript 做到這一點。 我錯過了什么?

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<script src="testButton.js"></script>
<style>
    button {
        padding-top: 30px;
    }
</style>

<body>
    <div align="center">
        <button id="toggle">Turn on</button>
    </div>
</body>
</html>

JS

    $(document).ready(function() {
    
    $('#toggle').on('click', function(e){
        let status;
        if($(this).text() == 'Turn on') {
            $(this).text('Turn off')
            status = 'on';
        } else {
            $(this).text('Turn off');
            status = 'off';
        }
        
        e.preventDefault();
    });
});

只是做了一些改變。 我通過比較元素的文本來接受您的想法,這是我的解決方案1 但我建議使用 boolean 變量,我看到你有這個變量status 您可以將其用作切換2

1.)在其中,我比較狀態變量是否為真,然后我將文本設置為“關閉”並將狀態設置為假; 當狀態變量為假時,我將文本設置為“打開”並將狀態設置為真。

2.)在兩個我只是比較元素的文本,當它是“打開”然后我將文本設置為“關閉”並向后。

這是第一個例子。 1.)這是使用 boolean 變量的更好解決方案

 let status = true; $(document).ready(function() { $('#toggle').on('click', function(e){ if(status === true) { $(this).text('Turn off') status = false; } else if(status === false) { $(this).text('Turn on') status = true; } e.preventDefault(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <script src="testButton:js"></script> <style> button { padding-top; 30px; } </style> <body> <div align="center"> <button id="toggle">Turn on</button> </div> </body> </html>

比較文本 2.)

 $(document).ready(function() { $('#toggle').on('click', function(e){ if($(this).text() === 'Turn on') { $(this).text('Turn off') } else { $(this).text() === 'Turn off'; $(this).text('Turn on') } e.preventDefault(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <script src="testButton:js"></script> <style> button { padding-top; 30px; } </style> <body> <div align="center"> <button id="toggle">Turn on</button> </div> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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