jq初始化函数
jQuery.fn.init =function(selector){
// 获取到选择列表
var list = document.querySelectorAll(selector);
// 当前对象的长度
this.length = list.length;
for(var i=0;i<list.length;i++){
//遍历类别对 this赋值
this[i] = list[i];
}
}
定义JQuery构造函数的显示原型
jQuery.fn =jQuery.prototype = {
constructor:jQuery,
jquery:"9.0.0",
length:0,
get(index){
return this[index];
},
jQuery 的构造函数
(function () {
// 匿名函数自执行
// jq的构造函数
function jQuery(selector) {
// 返回new 一个初始化函数
return new jQuery.fn.init(selector);
}
})();
显示与隐藏
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>w</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#hide").click(
function () {
$("#test").hide();
}
)
$("#show").click(
function () {
$("#test").show();
}
)
})
</script>
<style>
.box {
width: 300px;
margin: 0 auto;
/* border: 2px solid green; */
}
#test {
width: 296px;
height: 100px;
margin: 0 auto;
border: 2px solid red;
background-color: rgb(250, 205, 80);
}
</style>
</head>
<body>
<div class="box">
<input id="hide" type="button" value="隐藏">
<input id="show" type="button" value="显示">
<div id="test"></div>
</div>
</body>
</html>
添加类与删除类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
div {
height: 300px;
width: 300px;
background-color: orange;
}
.a {
background-color: #91DB4B;
}
</style>
<title>document</title>
<script src="./js/jquery-3.6.0.min.js"></script>
<script>
$(function () {
$("#d").mouseover(function () {
$(this).addClass('a');
}).mouseout(function () {
$(this).removeClass('a');
})
})
</script>
</head>
<body>
<div id="d">
小小jquery
</div>
</body>
</html>
extend方法
jQuery.extend = jQuery.fn.extend = function(){
//方法体...
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[ i ] || {};
i++;
}
if ( typeof target !== "object" && !isFunction( target ) ) {
target = {};
}
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
if ( ( options = arguments[ i ] ) != null ) {
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
if ( target === copy ) {
continue;
}
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = Array.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && Array.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
target[ name ] = jQuery.extend( deep, clone, copy );
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// 返回修改后的对象
return target;
}