js实现输入
使用HTML和JavaScript实现输入功能
在HTML中创建输入框,通过JavaScript获取用户输入的值
<input type="text" id="userInput" placeholder="请输入内容">
<button onclick="getInputValue()">提交</button>
<p id="output"></p>
<script>
function getInputValue() {
const inputValue = document.getElementById("userInput").value;
document.getElementById("output").innerText = `您输入的是: ${inputValue}`;
}
</script>
监听键盘事件实现即时输入反馈
通过添加事件监听器实时获取输入变化
document.getElementById("userInput").addEventListener("input", function(e) {
console.log("当前输入值:", e.target.value);
});
表单提交处理
处理表单提交事件,阻止默认提交行为并获取所有输入字段

<form id="myForm">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">登录</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
const formData = new FormData(event.target);
const data = Object.fromEntries(formData);
console.log("表单数据:", data);
});
</script>
使用prompt获取简单输入
快速获取用户输入的简单方法
const userName = prompt("请输入您的名字:");
if(userName) {
alert(`您好, ${userName}!`);
}
输入验证
添加基本的输入验证逻辑

function validateInput() {
const input = document.getElementById("userInput").value;
if(!input) {
alert("输入不能为空");
return false;
}
if(input.length < 3) {
alert("输入至少需要3个字符");
return false;
}
return true;
}
使用正则表达式验证特定格式
验证电子邮件格式的示例
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
const email = "example@domain.com";
if(validateEmail(email)) {
console.log("邮箱格式正确");
} else {
console.log("邮箱格式错误");
}
使用第三方库增强输入功能
使用jQuery简化输入处理
$("#userInput").on("change", function() {
console.log("输入值变化:", $(this).val());
});






