基础概念:
<input>
元素,通常是在用户完成输入并离开输入框时触发。优势:
类型及应用场景:
<input type="text">
):<select>
):<input type="checkbox">
)和单选按钮(<input type="radio">
):示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Demo</title>
</head>
<body>
<input type="text" id="textInput" placeholder="Enter text">
<select id="selectInput">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<input type="checkbox" id="checkboxInput">
<input type="radio" name="radioGroup" value="option1" id="radioInput1">
<input type="radio" name="radioGroup" value="option2" id="radioInput2">
<script>
const textInput = document.getElementById('textInput');
const selectInput = document.getElementById('selectInput');
const checkboxInput = document.getElementById('checkboxInput');
const radioInput1 = document.getElementById('radioInput1');
const radioInput2 = document.getElementById('radioInput2');
textInput.addEventListener('blur', () => {
console.log('Text input lost focus:', textInput.value);
});
textInput.addEventListener('change', () => {
console.log('Text input value changed:', textInput.value);
});
selectInput.addEventListener('blur', () => {
console.log('Select input lost focus:', selectInput.value);
});
selectInput.addEventListener('change', () => {
console.log('Select input value changed:', selectInput.value);
});
checkboxInput.addEventListener('blur', () => {
console.log('Checkbox input lost focus:', checkboxInput.checked);
});
checkboxInput.addEventListener('change', () => {
console.log('Checkbox input value changed:', checkboxInput.checked);
});
radioInput1.addEventListener('blur', () => {
console.log('Radio input 1 lost focus:', radioInput1.checked);
});
radioInput1.addEventListener('change', () => {
console.log('Radio input 1 value changed:', radioInput1.checked);
});
radioInput2.addEventListener('blur', () => {
console.log('Radio input 2 lost focus:', radioInput2.checked);
});
radioInput2.addEventListener('change', () => {
console.log('Radio input 2 value changed:', radioInput2.checked);
});
</script>
</body>
</html>
常见问题及解决方法:
通过上述示例代码和解释,可以清楚地了解blur和change事件的基础概念、优势、类型及应用场景,并解决常见问题。
领取专属 10元无门槛券
手把手带您无忧上云