jQuery 示例
jQuery由Google开发。要创建第一个jQuery示例,您需要使用包含jQuery的JavaScript文件。您可以从jquery.com下载jQuery文件,或者使用jQuery文件的绝对URL。
在这个jQuery示例中,我们使用的是jQuery文件的绝对URL。jQuery示例被写在script标签内。
让我们看一个简单的jQuery示例。
File: firstjquery.html
<!DOCTYPE html>  
<html>  
<head>  
 <title>First jQuery Example</title>  
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
 </script>  
 <script type="text/javascript" language="javascript">  
 (document).ready(function() {("p").css("background-color", "cyan");  
 });  
 </script>  
 </head>  
<body>  
<p>The first paragraph is selected.</p>  
<p>The second paragraph is selected.</p>  
<p>The third paragraph is selected.</p>  
</body>  
</html>  
输出:

$(document).ready()和$()
在$(document).ready()之间插入的代码只有在页面准备好执行JavaScript代码时才会执行一次。
可以使用简写符号$()来替代$(document).ready()。
$(document).ready(function() {  
$("p").css("color", "red");  
});  
上述代码等同于以下代码。
$(function() {  
$("p").css("color", "red");  
});  
让我们看一下使用jQuery缩写记法$()的完整示例。
File: shortjquery.html
<!DOCTYPE html>  
<html>  
<head>  
 <title>Second jQuery Example</title>  
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
 </script>  
 <script type="text/javascript" language="javascript">  
 (function() {("p").css("color", "red");  
 });  
 </script>  
 </head>  
<body>  
<p>The first paragraph is selected.</p>  
<p>The second paragraph is selected.</p>  
<p>The third paragraph is selected.</p>  
</body>  
</html>
输出:

function() { $("p").css("background-color", "cyan"); }
它将所有<p>标签或段落的背景颜色更改为青色。
 极客笔记
极客笔记