jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。表单选择是指使用 jQuery 选择器来操作 HTML 表单元素,如输入框、下拉菜单、按钮等。
$('#id')、$('.class')、$('tagname') 等。$('div.class')、$('#id .class') 等。$('[attribute=value]')、$('[attribute!=value]') 等。$('input')、$('select')、$('textarea')、$('button') 等。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" id="username" placeholder="Username">
<input type="password" id="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#myForm').submit(function(event) {
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
if (username === '' || password === '') {
alert('Please fill in all fields');
} else {
alert('Form submitted successfully');
}
});
});
</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Form Modification</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form>
<input type="text" id="name" placeholder="Name">
<button type="button" id="changeValue">Change Value</button>
</form>
<script>
$(document).ready(function() {
$('#changeValue').click(function() {
$('#name').val('New Value');
});
});
</script>
</body>
</html>原因:
解决方法:
$(document).ready() 确保 DOM 元素加载完成后再执行 jQuery 代码。$(document).ready(function() {
// 你的 jQuery 代码
});原因: 表单默认的提交行为会导致页面刷新。
解决方法:
使用 event.preventDefault() 阻止表单默认提交行为。
$('#myForm').submit(function(event) {
event.preventDefault();
// 你的处理逻辑
});通过以上内容,你应该对 jQuery 表单选择有了全面的了解,并能够解决常见的相关问题。
没有搜到相关的文章