HTML 按钮单击事件示例
# HTML 按钮单击事件示例
以下是几种不同的方式来实现按钮的单击事件:
## 1. 最简单的 HTML 按钮单击事件
```html
<!DOCTYPE html>
<html>
<head>
<title>按钮单击事件示例</title>
</head>
<body>
<!-- 方法1:直接在HTML中使用onclick属性 -->
<button οnclick="alert('按钮被点击了!')">点击我</button>
<!-- 方法2:调用JavaScript函数 -->
<button οnclick="handleClick()">调用函数</button>
<script>
// JavaScript函数
function handleClick() {
console.log("按钮被点击了");
alert("你调用了handleClick函数!");
}
</script>
</body>
</html>
## 2. 使用JavaScript添加事件监听器
```html
<!DOCTYPE html>
<html>
<head>
<title>按钮事件监听器</title>
</head>
<body>
<button id="myButton">点击我</button>
<script>
// 获取按钮元素
const button = document.getElementById('myButton');
// 添加点击事件监听器
button.addEventListener('click', function() {
console.log("按钮被点击了");
alert("通过addEventListener添加的事件被触发!");
// 可以在这里添加更多逻辑
this.style.backgroundColor = 'red';
this.textContent = '已点击';
});
</script>
</body>
</html>
## 3. 带参数的按钮点击事件
```html
<!DOCTYPE html>
<html>
<head>
<title>带参数的按钮事件</title>
</head>
<body>
<button οnclick="greet('张三')">问候张三</button>
<button οnclick="greet('李四')">问候李四</button>
<script>
function greet(name) {
alert(`你好,${name}!`);
}
</script>
</body>
</html>
## 4. 阻止默认行为的按钮点击事件
```html
<!DOCTYPE html>
<html>
<head>
<title>阻止默认行为</title>
</head>
<body>
<form>
<button type="submit" id="submitBtn">提交表单</button>
</form>
<script>
document.getElementById('submitBtn').addEventListener('click', function(e) {
e.preventDefault(); // 阻止表单默认提交行为
alert("表单提交被阻止,执行自定义操作");
// 这里可以添加AJAX提交等自定义逻辑
});
</script>
</body>
</html>
## 5. 事件委托(适合动态添加的按钮)
```html
<!DOCTYPE html>
<html>
<head>
<title>事件委托</title>
</head>
<body>
<div id="buttonContainer">
<button class="action-btn">按钮1</button>
<button class="action-btn">按钮2</button>
</div>
<button id="addBtn">添加新按钮</button>
<script>
// 事件委托 - 处理所有.action-btn的点击
document.getElementById('buttonContainer').addEventListener('click', function(e) {
if(e.target.classList.contains('action-btn')) {
alert(`你点击了 ${e.target.textContent}`);
}
});
// 添加新按钮
document.getElementById('addBtn').addEventListener('click', function() {
const btnCount = document.querySelectorAll('.action-btn').length + 1;
const newBtn = document.createElement('button');
newBtn.className = 'action-btn';
newBtn.textContent = `按钮${btnCount}`;
document.getElementById('buttonContainer').appendChild(newBtn);
});
</script>
</body>
</html>
以上示例涵盖了按钮单击事件的不同实现方式,可以根据具体需求选择合适的方法。