jQuery的bind()
方法用于將事件處理程序綁定到元素上。以下是一些實際開發中的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Bind Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="myButton">Click me!</button>
<script>
$("#myButton").bind("click", function() {
alert("Button clicked!");
});
</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>jQuery Bind Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="myDiv" style="width: 100px; height: 100px; background-color: red;">Hover over me!</div>
<script>
$("#myDiv").bind("mouseover", function() {
$(this).css("background-color", "blue");
});
$("#myDiv").bind("mouseout", function() {
$(this).css("background-color", "red");
});
</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>jQuery Bind Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
<script>
$("#myForm").bind("submit", function(event) {
event.preventDefault(); // 阻止表單默認提交行為
var username = $("input[name='username']").val();
var password = $("input[name='password']").val();
alert("Username: " + username + ", Password: " + password);
});
</script>
</body>
</html>
這些例子展示了如何使用jQuery的bind()
方法為元素綁定不同類型的事件處理程序。