jQuery快速入门第一课
jQuery是一个JavaScript库,它封装了一个$函数。
jQuery安装
前往https://jquery.com/download下载jQuery。目前,jQuery有v1、v2和v3。
v1兼容IE6,v3只支持最新的浏览器。
下载后,放到相应的目录里,在html中引入。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery</title>
<script src="js/jquery-1.11.2.js"></script>
</head>
<body>
<script>
</script>
</body>
</html>
jQuery中的DOM操作
jQuery通过选择器来操作DOM
1.1 ID选择器
在普通的JavaScript中,如果需要通过ID寻找DOM并操作,需要:
document.getElementById('')
而在jQuery中,只需
$("#id")
例子
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery</title>
<script src="js/jquery-1.11.2.js"></script>
</head>
<body>
<p id="aaa">123</p>
<script>
$(function(){ //相当于window.οnlοad=function(){}
$("#aa").click(function(){/*相当document.getElementById('aa').οnclick=function(){}*/
$("#aa").hide()//隐藏
});
})
</script>
</body>
</html>
运行以上代码网页上会出现123,点击它,它会隐藏。
1.2 类选择器
在普通的JavaScript中,如果需要通过class寻找DOM并操作,需要:
document.getElementByClassName('')
而在jQuery中只需
$(".class")
例子
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery</title>
<script src="js/jquery-1.11.2.js"></script>
</head>
<body>
<p id="aaa">123</p>
<script>
$(function(){ //相当于window.οnlοad=function(){}
$(".aa").click(function(){/*相当document.getElementByClassName('aa').οnclick=function(){}*/
$(".aa").hide()//隐藏
});
})
</script>
</body>
</html>
此例功能与上例一致。
1.3元素选择器
在普通的JavaScript中,如果需要通过标签名寻找DOM并操作,需要:
document.getElementByTagName('')
而在jQuery中,只需
$("tag")
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery</title>
<script src="js/jquery-1.11.2.js"></script>
</head>
<body>
<p id="aaa">123</p>
<script>
$(function(){ //相当于window.οnlοad=function(){}
$("p").click(function(){/*相当document.getElementByTagName('aa').οnclick=function(){}*/
$("p").hide()//隐藏
});
})
</script>
</body>
</html>
此例功能与上例一致。