我在網上搜索了很多,但出于某種原因,我的代碼 = 沒有作業;
我的 JavaScript:
let a = document.getElementById("a");
let b = document.getElementById("b");
let c = document.getElementById("c");
let button = document.getElementById("button");
button.onclick = function() {
var info = {"a": a.value, "b": b.value, "c": c.value};
console.log(info.a info.b info.c);
}
除了 C 之外的一切都有效,它是一個下拉選單(A 和 B 是文本框)。
HTML:
<button type = "button" id = "button>Button</button>
<input type = "text" id = "a">A</input>
<br><br>
<input type = "text" id = "b">
<br><br>
<select name = "c" class = "c">
<option value = "c1" class = "c" selected>c1</option>
<option value = "c2" class = "c">c2</option>
<option value = "c3" class = "c">c3</option>
uj5u.com熱心網友回復:
您的 HTML 有問題。
<input type = "text" id = "a">A</input>錯了,應該是這樣的:<input type = "text" id = "a" value="A"/>只有這樣你才能得到這個欄位的“值”。第二個文本框也是如此。還要在選擇框中添加“id”。
uj5u.com熱心網友回復:
- 您缺少 id = "button 的結束引號
- 沒有名為 c 的 id。
uj5u.com熱心網友回復:
第一個問題是<select name = "c" class = "c">您必須將其設為 id 而不是 class。Button HTML 也有點錯誤<button type = "button" id = "button>Button</button>,而是應該<button type = "button" id = "button">Button</button>
在它應該作業之后。如果它仍然不起作用,那么您可以將 JS 代碼包裝在 window.onload 函式中。
window.onload = function() {
let a = document.getElementById("a");
let b = document.getElementById("b");
let c = document.getElementById("c");
let button = document.getElementById("button");
button.onclick = function() {
var info = {"a": a.value, "b": b.value, "c": c.value};
console.log(info.a info.b info.c);
}
}
uj5u.com熱心網友回復:
我將首先介紹其他人提出的一些觀點。
缺少引號
id="button會使您的 HTML 無效。沒有元素
id。select沒有
</select>標簽。在選項和選項上具有相同的類別
select似乎很奇怪。您所歸屬的文本內容
A應作為value屬性添加到元素中,并且沒有理由使用</input>tag。
所以我已經洗掉了所有這些問題。
我已經切換了類的所有 id 以使事情保持一致,并用于
querySelector拾取這些元素。我完全洗掉了按鈕 ID。我
addEventListener在按鈕上使用了它,而不是onclick它是一種更現代的處理事件的方法。
let a = document.querySelector('.a');
let b = document.querySelector('.b');
let c = document.querySelector('.c');
let button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
const info = { a: a.value, b: b.value, c: c.value };
console.log(info.a info.b info.c);
}
<button type="button">Button</button>
<input type="text" value="A" class="a">
<br><br>
<input type="text" class="b">
<br><br>
<select name="c" class="c">
<option value="c1" selected>c1</option>
<option value="c2">c2</option>
<option value="c3">c3</option>
</select>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471220.html
標籤:javascript html 功能 点击 落下
上一篇:如何使用引導程式添加6行段落?
