JavaScript中的radio
点击事件是指当用户点击单选按钮(<input type="radio">
)时触发的事件。以下是关于这个问题的基础概念、相关优势、类型、应用场景以及可能遇到的问题和解决方法。
addEventListener
方法绑定事件。.on('click', handler)
方法绑定事件。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Radio Click Event</title>
</head>
<body>
<form>
<input type="radio" name="choice" value="option1"> Option 1<br>
<input type="radio" name="choice" value="option2"> Option 2<br>
<input type="radio" name="choice" value="option3"> Option 3<br>
</form>
<p id="result"></p>
<script>
document.querySelectorAll('input[name="choice"]').forEach(radio => {
radio.addEventListener('click', function() {
document.getElementById('result').textContent = `You selected: ${this.value}`;
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Radio Click Event</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form>
<input type="radio" name="choice" value="option1"> Option 1<br>
<input type="radio" name="choice" value="option2"> Option 2<br>
<input type="radio" name="choice" value="option3"> Option 3<br>
</form>
<p id="result"></p>
<script>
$('input[name="choice"]').on('click', function() {
$('#result').text(`You selected: ${$(this).val()}`);
});
</script>
</body>
</html>
this
关键字引用当前被点击的单选按钮。通过以上方法和示例代码,可以有效地处理JavaScript中的radio
点击事件。
没有搜到相关的文章