jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。jQuery 的核心特性之一是它的文档就绪(document ready)函数,它允许你在 DOM(文档对象模型)完全加载并准备好后执行 JavaScript 代码。
jQuery 页面加载后执行的代码主要有以下几种类型:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Document Ready Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1 id="welcome">Hello, World!</h1>
<script>
$(document).ready(function() {
// 在 DOM 完全加载后执行
$('#welcome').css('color', 'blue');
});
// 或者使用简写形式
$(function() {
$('#welcome').css('color', 'red');
});
</script>
</body>
</html>
原因:
$(document).ready()
中。解决方法:
$(document).ready()
中。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Document Ready Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1 id="welcome">Hello, World!</h1>
<script>
$(document).ready(function() {
$('#welcome').css('color', 'blue');
});
</script>
</body>
</html>
通过以上方法,可以确保 jQuery 代码在页面加载后正确执行。
领取专属 10元无门槛券
手把手带您无忧上云