**
JQuery基础(一)
**
介绍:
JQuery是一个非常优秀的轻量级js框架,提供了HTML文档文档操作、事件处理、动画设计和Ajax交互操作。JQuery的理念是write less do more。
使用JQuery框架必须要先下载JQuery的一个库,可以通过多种方法在自己写的代码中添加 jQuery库。 常使用的方法有:
- 从 jquery.com 下载 jQuery 库(https://jquery.com/download/)
- 从 CDN 中载入 jQuery, 如从 Google 中加载 jQuery(后面代码部分展示)
将下载好的 jQuery 库文件或地址导入到script标签中:
<script src="js/jquery-3.4.1.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Jquery中定义变量的方法:
var obj1=$(’#div1’);
js中定义变量的方法:
var obj2=document.document.getElementById(“div1”);
jquery对象与js对象之间的转换:
-
jquery转js:
var obj_change_js=$obj2[0].innerText; //$obj.get(1).innerText console.log("jquery转js"+obj_change_js);
-
js转jquery:
var obj_change_jquery=$(obj).text(); //text("")中的内容会被显示在显示界面,为空表示显示原来内容 console.log("js转jquery"+obj_change_jquery);
jquery页面载入的两种方式:
①
$(function() {
// 代码区…
});
②
$(document).ready(function(){
//代码区…
});
Jquery的选择器:
- id选择器
var id=$("#id1"); - 元素选择器
var h1=$(“h1”); - 类选择器
$(".class"); - 通配符选择器
$("*"); - 群组选择器
$("#id,span,div)
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-3.4.1.js"></script>
</head>
<body>
<h1 id="h1">第1个h1标签</h1>
<h1 id="h2">第2个h1标签</h1>
<h1 id="h3">第3个h1标签</h1>
<h1 id="h4">第4个h1标签</h1>
<h1 id="h5">第5个h1标签</h1>
<table>
<tr><td>value 1</td></tr>
<tr><td>Value 2</td></tr>
<tr><td>Value 3</td></tr>
<tr><td>Value 4</td></tr>
</table>
<script>
//页面载入两种方式
// $(function(){
// });
// $(document).ready(function(){
// });
var first_h=$('h1:first');//获取第一个标签
console.log(first_h.text());
var last_h=$('h1:last');//获取最后一个标签
console.log(last_h.text());
var except_h=$('h1:not("#h3")');//获取除id为h3的其他元素
console.log(except_h.text());
// :even,匹配所有索引值为偶数的元素,从 0 开始计数
console.log($("tr:even").text());
console.log($("h1:even").text());
// :odd,匹配所有索引值为奇数的元素,从 0 开始计数
console.log($('tr:odd').text());
console.log($('h1:odd').text());
console.log($('h1:eq(2)').text());// 匹配一个给定索引值的元素,返回的仍然是JQuery对象,从0开始
console.log($('h1:gt(2)').text());// 匹配所有大于给定索引值的元素,返回的仍然是JQuery对象,从0开始
console.log($("tr:lt(2)").text()); // 匹配所有小于给定索引值的元素,返回的仍然是JQuery对象,从0开始
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-3.4.1.js"></script>
</head>
<body>
<ul>
<li>第1个ul下的li</li>
<li>第2个ul下的li</li>
<li>第3个ul下的li</li>
<li>第4个ul下的li</li>
<li>第5个ul下的li</li>
<li>第6个ul下的li</li>
</ul>
<script>
var child_ul_first=$('ul li:first-child').text();
console.log(child_ul_first);
var child_ul_last=$('ul li:last-child').text();
console.log(child_ul_last);
console.log($('ul li:nth-child(3)').text()); //匹配其父元素下的第3个子元素,下标从1开始
console.log($("ul li:nth-child(odd)").text()); //匹配其父元素下的奇数个子元素(相当于2n+1),下标从1开始
console.log($("ul li:nth-child(even)").text()); //匹配其父元素下的偶数个子元素(相当于2n),下标从1开始
</script>
</body>
</html>