Nic*_*ani 3 javascript refactoring scope
我是一个JS noob试图让这个"你好mr./miss yourname!" 清洁.我没有看到在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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
谢谢你的任何建议.
您可以使用三元运算符
alert('Hello ' + ( a === "M" ? "Mr." : "Miss" ) + " " + x + "!");
Run Code Online (Sandbox Code Playgroud)
即
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
alert('Hello ' + ( a === "M" ? "Mr." : "Miss" ) + " " + x + "!");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |