我是JS菜鸟,试图将其设为“您好,先生/小姐!”清洁。
我没有办法在if / else内部重构警报,因为那样我就失去了var b的值。

JS:

<script>
    "use strict";
    window.onload = function () {
        let form1 = document.getElementById('myForm');
        form1.addEventListener('submit', helloYou);
        function helloYou() {
            let x = document.getElementById("1").value;
            let a = document.getElementById('3').value;
            if ( a === "M") {
                let b = "Mr.";
                alert('Hello ' + b + " " + x + "!");
            }
            else {
                let b = "Miss";
                alert('Hello ' + b + " " + x + "!");
            }
        }
    }
</script>

HTML:
<body>
    <form id="myForm">
        Write your name:
        <input type="text" name="yourname" id="1" placeholder="name">
        <select name="gender" id="3">
            <option value="M">Male</option>
            <option value="F">Female</option>
        <input type="submit" name="submission" id="2" value="TRY ME">
    </form>
</body>

感谢您的任何建议。

最佳答案

您可以使用三元运算符

alert('Hello ' + ( a === "M" ? "Mr." : "Miss" ) + " " + x + "!");


   function helloYou() {
        let x = document.getElementById("1").value;
        let a = document.getElementById('3').value;
        alert('Hello ' + ( a === "M" ? "Mr." : "Miss" ) + " " + x + "!");
    }

关于javascript - 找不到重构警报(锻炼)的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49755379/

10-11 08:14