在JavaScript中,清空输入框内容可以通过多种方式实现。以下是一些常见的方法:
value
属性为空字符串你可以直接将输入框的value
属性设置为空字符串来清空其内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clear Input Box</title>
</head>
<body>
<input type="text" id="myInput" value="Hello World">
<button onclick="clearInput()">Clear</button>
<script>
function clearInput() {
document.getElementById('myInput').value = '';
}
</script>
</body>
</html>
querySelector
选择器如果你有多个输入框,可以使用querySelector
来选择特定的输入框并清空其内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clear Input Box</title>
</head>
<body>
<input type="text" class="myInput" value="Hello World">
<button onclick="clearInput()">Clear</button>
<script>
function clearInput() {
document.querySelector('.myInput').value = '';
}
</script>
</body>
</html>
如果你在一个表单中,可以使用表单的reset
方法来清空所有输入框的内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clear Input Box</title>
</head>
<body>
<form id="myForm">
<input type="text" name="myInput" value="Hello World">
<button type="button" onclick="clearForm()">Clear</button>
</form>
<script>
function clearForm() {
document.getElementById('myForm').reset();
}
</script>
</body>
</html>
value
属性为空字符串是最简单和直接的方法。querySelector
可以选择特定的输入框,适用于复杂的页面结构。reset
方法非常方便。通过以上方法,你可以根据具体需求选择最适合的方式来清空输入框内容。
领取专属 10元无门槛券
手把手带您无忧上云