创建一个hello.html具有以下内容的文件:
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<div>
<p id="hello">Some random text</p>
</div>
<script xx_src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function() {
$('#hello').text('Hello, World!');
});
</script>
</body>
</html>JSBin现场演示
在网络浏览器中打开此文件。结果,您将看到一个包含以下文本的页面:Hello, World!
从jQuery CDN加载jQuery库:
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
这引入了$全局变量,即jQuery函数和名称空间的别名。
请注意,在包含jQuery时犯的最常见错误之一是无法加载可能依赖或利用它的任何其他脚本或库之前的库。
延迟当jQuery检测到DOM(文档对象模型)为“就绪”时要执行的功能:
// 当文档准备就绪时,执行此功能...。
$(document).ready(function() { ... });
// 常用的速记版本(与上述行为相同)
$(function() { ... });
DOM准备就绪后,jQuery将执行上面显示的回调函数。在我们的函数内部,只有一个调用可以完成2个主要任务:
获取id属性等于hello(我们的选择器#hello)的元素。使用选择器作为传递的参数是jQuery功能和命名的核心。整个库实际上是从扩展document.querySelectorAll MDN演变而来的。
将text()选定元素的内部设置为Hello, World!。
# ↓ - Pass a `selector` to `$` jQuery, returns our element
$('#hello').text('Hello, World!');
# ↑ - Set the Text on the element
有关更多信息,请参考jQuery-文档页面。