九、jQuery
目錄:初識jQuery及公式、jQuery選擇器、jQuery事件、jQuery操作DOM元素
1.初識jQuery及公式
jQuery庫,里面存在大量的JavaScript。
1)獲取jQuery
jQuery官網(wǎng):http://jquery.com,可以下載放入項目中使用。
還可以使用在線cdn加速鏈接,jQuery cdn加速網(wǎng)址:http://www.bootcdn.cn/jquery/
2)公式:$(selector).action()
例:a鏈接被點擊跳出彈窗
<a href=" " id="test-jquery">點我</a>
<script>
//原生的JS代碼
var id = document.getElementById('test-jquery');
id.click(…);
//用jQuery的選擇器,本質上是CSS選擇器
$('#text-jQuery').click(function() {
alert('hello jquery');
})
</script>
2.jQuery選擇器
1)原生的js選擇器(太少且不好記)
①標簽
document.getElementsByTagName();
②id
document.getElementById();
③類
document.getElementsByClassName();
2)jQuery中CSS選擇器都能用
①標簽
例:p標簽
$('p').action();
②id
$('#id').action();
③類
$('.class').action();
jQuery文檔工具類:http://jquery.cuishifeng.cn/
3.jQuery事件
鼠標事件、鍵盤事件、其它事件
當網(wǎng)頁元素加載完畢之后,響應事件:
$(document).ready(function() { })
等同于
$(function() { })
例:獲取鼠標當前的一個坐標
<html>
<head>
<title>獲取鼠標當前的一個坐標</title>
<style>
#divMove {
width:500px;
height:500px;
border:1px solid red;
}
</style>
</head>
<body>
mouse:<span id="mouseMove"></span>
<div id="divMove">在這里鼠標移動試試</div>
<script>
$(function() {
$('#divMove').mousemove(function(e) {
$('#mouseMove').text('x:'+e.pageX+'y:'+e.pageY)
})
})
</script>
</body>
</html>
4.jQuery操作DOM元素
例:
<ul id="test-ul">
<li class="js">JavaScript</li>
<li name="java">Java</li>
</ul>
1)節(jié)點文本操作
$('#test-ul li[name=java]').text();//獲得值
$('#test-ul li[name=java]').text('值');//設置值
$('#test-ul').html();//獲得值
$('#test-ul').html('值');//設置值
2)CSS的操作
$('#test-ul li[name=java]').css({"color","red"})
3)元素的顯示和隱藏
本質:CSS的display:none;
$('#test-ul li[name=java]').show();//顯示
$('#test-ul li[name=java]').hide();//隱藏
總結:前端三劍客學習技巧
1)鞏固JS(看jQuery源碼)
2)鞏固HTML+CSS(扒網(wǎng)站,全部拷下來,然后對應修改看效果)