jquery
jquery 代码书写位置的三种
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| $(document).ready(function () { var box = document.getElementById("box"); console.log(box); });
$().ready(function () { var box = document.getElementById("box"); console.log(box); });
$(function () { var box = document.getElementById("box"); console.log(box); });
|
dom 元素加载完就会触发 ready
jquery 的特点:
- 强大的选择器
1 2 3 4
| <script> var $h1 = $("h1"); console.log($h1); </script>
|
链式操作
原生 js 取到的 dom 对象和 jquery 取到的不一样。
原生 js 取到的对象不能使用 jquery 里面的方法。
jquery 取到的对象也不能使用使用原生的 js 方法。
原生 js 和 jquery 元素之间可以相互转化:
原生 js 转 jquery: $(dom 对象);
jquery 转原生 js: $jquery 对象[0];
jquery 取到的永远是一个数组
基础选择器
1 2 3 4 5 6 7 8 9
| <div id="box">不错</div> <div class="className">你好</div> <p>p标签</p> <script> $("*").css("border", "2px solid black"); $("#box").css("background", "red"); $(".className").css("background", "green"); $("p").css("background", "blue"); </script>
|
层级选择器:可参考 CSS3 选择器
1 2 3 4 5 6 7
| <div class="wrapper"> <div class="content">啊这</div> <p>不错</p> </div> <script> $(".wrapper p").css("color", "green"); </script>
|
属性选择器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <div name="t">不错</div> <div title="j">就这</div> <div title="j-t">啊这</div> <div title="jr">棒</div> <div title="ttj">强</div> <div title="qgrp">加油</div> <div title="qgp">冲</div> <p id="xyq">很好</p> <script> $("[name]").css("background", "red"); $("[title=j]").css("background", "green"); $("div[title!=j]").css("background", "blue"); $("div[title|=j]").css("background", "red"); $("div[title^=j]").css("background", "yellow"); $("div[title$=j]").css("background", "hotpink"); $("div[title*=gr]").css("background", "purple"); $("div[title~=gr]").css("background", "purple"); </script>
|
腾讯云
对象存储
自定义插件:
1 .给 jquery 对象本身扩展方法
1 2 3 4 5
| $.extend( { 函数名:function(){ 函数体 } });
|
使用:$.函数名();
2. 给 jquery DOM 对象扩展方法
1 2 3 4 5 6 7 8
| $.fn.extend( { 函数名:function(){ $(this).jquery方法;
return $(this); } });
|
或者:
1 2 3 4 5 6
| $.fn.函数名 = function () { $(this).jquery方法;
return $(this); };
|
使用:
$(dom 对象).函数名();
attr 方法和 prop 方法都是用来设置属性值的,区别在于 attr 方法用于设置一般属性,而 prop 用来设置特殊属性。如果是自定义属性,使用 attr 方法来进行设置。当然,设置自定义属性,还可以使用 jquery 中提供的 data 方法。
hide()方法可以隐藏元素
show() 方法可以展示元素
hover() 方法可以设置 hover 需传递两个参数,是两个函数,第一个函数处理·移入,第二个函数处理移出
user-select:none;禁止选中 CSS
$(dom).load(html 页面) :可以在一个页面中加载其他页面