背景:
<input type="radio">,該標簽表示的是單選按鈕,這個類型相對於其他類型的獲取,比較特殊,特此記錄一下。
獲取方式:
1. 使用選擇器直接獲取(注意選擇器這種方式的使用);
1 <html>
2 <head>
3 <title>標題示例</title>
4 <meta charset="UTF-8">
5 <style>
6 </style>
7 </head>
8 <body>
9 <form>
10 <p>Please select your preferred contact method:</p>
11 <div>
12 <input type="radio" id="contactChoice1"
13 name="contact" value="email">
14 <label for="contactChoice1">Email</label>
15
16 <input type="radio" id="contactChoice2"
17 name="contact" value="phone">
18 <label for="contactChoice2">Phone</label>
19
20 <input type="radio" id="contactChoice3"
21 name="contact" value="mail">
22 <label for="contactChoice3">Mail</label>
23 </div>
24 <div>
25 <button type="button">Submit</button>
26 </div>
27 </form>
28 <script>
29 let ele = document.querySelector('button') 30 let form = document.querySelector('form') 31 ele.addEventListener('click', function () { 32 let x = form.querySelector("input[name='contact']:checked") 33 console.log(x.value) 34 }) 35 </script>
36 </body>
37 </html>
2. 使用FormData對象獲取;
1 <html>
2 <head>
3 <title>標題示例</title>
4 <meta charset="UTF-8">
5 <style>
6 </style>
7 </head>
8 <body>
9 <form>
10 <p>Please select your preferred contact method:</p>
11 <div>
12 <input type="radio" id="contactChoice1"
13 name="contact" value="email">
14 <label for="contactChoice1">Email</label>
15
16 <input type="radio" id="contactChoice2"
17 name="contact" value="phone">
18 <label for="contactChoice2">Phone</label>
19
20 <input type="radio" id="contactChoice3"
21 name="contact" value="mail">
22 <label for="contactChoice3">Mail</label>
23 </div>
24 <div>
25 <button type="button">Submit</button>
26 </div>
27 </form>
28 <script>
29 let ele = document.querySelector('button') 30 let form = document.querySelector('form') 31 ele.addEventListener('click', function () { 32 var data = new FormData(form); 33 var output = ""; 34 for (const entry of data) { 35 output = entry[0] + "=" + entry[1] + "\r"; 36 }; 37 console.log(output) 38 }) 39 </script>
40 </body>
41 </html>
參考地址:
2. https://blog.csdn.net/qq_39822451/article/details/82753282