jQuery 安装
需要下载 jQuery 库,然后把它包含在希望使用的网页中。
jQuery 语法
jQuery 语法是为 HTML 元素的选取编制的,可以对元素执行某些操作。
基础语法是:$(selector).action()
- 美元符号定义 jQuery
- 选择符(selector)“查询”和“查找” HTML 元素
- jQuery 的 action() 执行对元素的操作
隐藏
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
$(document).ready(function(){
$("button").click(function(){ (要点击的地方 “p”)
$("h2").hide(); //$(要隐藏的标签,“p”"h2" this “.类名” id)
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
文档就绪函数
jQuery 函数位于一个 document ready 函数中:
$(document).ready(function(){
--- jQuery functions go here ----
});
这是为了防止文档在完全加载(就绪)之前运行 jQuery 代码。
jQuery选择器
jQuery 元素选择器
jQuery 使用 CSS 选择器来选取 HTML 元素。
$("p") 选取 <p> 元素。
$("p.intro") 选取所有 class="intro" 的 <p> 元素。
$("p#demo") 选取所有 id="demo" 的 <p> 元素。
jQuery 属性选择器
jQuery 使用 XPath 表达式来选择带有给定属性的元素。
$("[href]") 选取所有带有 href 属性的元素。
$("[href='#']") 选取所有带有 href 值等于 "#" 的元素。
$("[href!='#']") 选取所有带有 href 值不等于 "#" 的元素。
$("[href$='.jpg']") 选取所有 href 值以 ".jpg" 结尾的元素。
jQuery CSS 选择器
jQuery CSS 选择器可用于改变 HTML 元素的 CSS 属性。
下面的例子把所有 p 元素的背景颜色更改为红色:
实例
$("p").css("background-color","red");
jQuery事件