<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 200px;
height: 50px;
margin: 20px auto;
text-align: center;
border: 1px solid black;
line-height: 50px;
font-size: 18px;
color: gray;
}
</style>
</head>
<body>
<div id="box">id</div>
<div class="child">class类</div>
<div>标签1</div>
<div>标签2</div>
<script>
//函数自执行
(function() {
function jQuery(str) {
//html方法 重置innerhtml的内容
jQuery.prototype.html = function(html) {
//判断html里面是否输入空值
if (html == undefined || html == "") {
return
}
//遍历当前获取的节点 重置innerhtml的内容
for (let i = 0; i < result.length; i++) {
result[i].innerHTML = html
}
}
//css方法 重置css样式
jQuery.prototype.css = function(style, value) {
//判断是否输入空值
if (style == undefined || style == "" || value == undefined || value == "") {
return
}
//遍历当前获取的节点 重置css的样式
for (let i = 0; i < result.length; i++) {
result[i].style[style] = value
}
}
//定义结果对象
function Result() {}
//把css和html方法赋值到jquery身上
Result.prototype = jQuery.prototype
let id = null; //id
let gather = null; //class和tag
//通过id获取节点
if (str[0] == "#") {
let a = str.slice(1)
id = document.getElementById(a)
//通过class获取节点
} else if (str[0] == ".") {
let ids = str.slice(1)
gather = document.getElementsByClassName(ids)
//通过标签获取节点
} else {
gather = document.getElementsByTagName(str)
}
//装jquery方法
let result = new Result()
if (id != null) {
result[0] = id
result["length"] = 1
} else {
//循环class集合,把得到的集合装入nodes
for (let i = 0; i < gather.length; i++) {
result[i] = gather[i];
}
result["length"] = gather.length
}
return result
}
//提供自定义方法的接口
jQuery.fn = jQuery.prototype
//提供调用jquery的变量名
window.$ = jQuery;
})() //函数自执行
$("div").html("一个和尚,挑水喝")
$("#box").css("background", "pink")
$(".child").html("我是一个字符串")
$(".child").css("color", "red")
console.log($("div"));
</script>
</body>
</html>