Using “if/else” with OnClick

后端 未结 5 1274
悲&欢浪女
悲&欢浪女 2021-01-06 08:51

First of all, is it even possible to write if/else statements directly in html with onclick attribute? And if so, why is my code not working?

So this is a button. T

相关标签:
5条回答
  • 2021-01-06 09:35

  • Alert on nav page
  •            <script>
                  function myFunction() {
                alert("You Are Not Signed In!");
                       }
                     </script>
    
0 讨论(0)
  • 2021-01-06 09:36

    Hmm but how about for something like this:

    <a href="#" onclick="if (a_function_to_get_language() == 'en') {
        alert('Some message');
    }
    else {
        alert('Some message in a different language');
    }">Action</a>
    
    0 讨论(0)
  • 2021-01-06 09:38

    sweetamylase's reply is best but you may also consider:

    If your onclick= assignment is enclosed in double quotes (onclick="...") then try using only single quote characters inside of those double quotes (or vice versa).

    This can make things easier when you need to make assignments to the onclick event when inserting elements dynamically and having separate script functions isn't really a good option.

    Example:

    <button onclick="alert('Do this'+' and that')">Press This</button>
    
    0 讨论(0)
  • 2021-01-06 09:43

    Just DON'T put it in the onclick attribute.

    Use

    <INPUT TYPE="button" NAME="drop" id="dropbutton" style="background-color:#D1E8D5;" VALUE="Släpp ankare ">
    <script>
    document.getElementById('dropbutton').onclick = function() {
        if (Calc.Input.value == '' || Calc.Input.value == '0') {
             window.alert("Please enter a number");
        } else {
            document.getElementById('dropbutton').value=' Justera längd ';
            document.getElementById('length').innerHTML = Calc.Input.value;
            document.getElementById('dropbutton').style.backgroundColor = '#FFF6B3';
        }
        return false;
    }
    </script>
    
    0 讨论(0)
  • 2021-01-06 09:45

    The reason your code is not working is because you need to escape your " quotation marks, otherwise it will be interpreted as the HTML attribute symbol.

    And I agree with the others, it is a bad practice to write your JavaScript inline inside your HTML.

    0 讨论(0)
  • 提交回复
    热议问题