捕获输入数据时是否必须使用event.target取决于你要捕获的输入数据的类型和你想要的功能。
如果你只是想简单地获取输入字段的值,你可以不使用event.target。你可以直接从输入字段的引用中获取值。
示例代码:
HTML:
JavaScript:
const myInput = document.getElementById("myInput");
const myButton = document.getElementById("myButton");
myButton.addEventListener("click", function() {
const inputValue = myInput.value;
console.log(inputValue);
});
在上面的示例中,我们通过直接从输入字段的引用(myInput)中获取值,而不使用event.target。
然而,如果你想根据不同的输入字段执行不同的操作,或者想要获取更多关于事件的信息(如事件源),则需要使用event.target。
示例代码:
HTML:
JavaScript:
const myInputs = document.querySelectorAll(".myInput");
function handleInput(event) {
const inputType = event.target.type;
const inputValue = event.target.value;
if (inputType === "text") {
console.log("文本输入字段的值:" + inputValue);
} else if (inputType === "checkbox") {
console.log("复选框的值:" + event.target.checked);
} else if (inputType === "radio") {
console.log("单选框的值:" + inputValue);
}
}
myInputs.forEach(function(input) {
input.addEventListener("input", handleInput);
});
在上面的示例中,我们使用了event.target来获取不同类型的输入字段的值,并根据输入字段的类型执行不同的操作。
下一篇:捕获输入字段中的文本