手写jQ对id和class可以做处理:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>温故而知新</title>
<style></style>
</head>
<body>
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
</body>
<!-- <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> -->
<script>
/*
手写JQ
*/
//jQuery库 封闭作用域
(function () {
function jQuery(selector) {
return new jQuery.prototype.init(selector)
}
jQuery.prototype.init = function (selector) {
//选出dom并且包装成jQuery对象,返回
//就拿id和class来处理
this.length = 0;
if (selector.indexOf('.') != -1) {
var dom = document.getElementsByClassName(selector.slice(1));
} else if (selector.indexOf('#') != -1) {
var dom = document.getElementsByClassName(selector.slice(1));
}
if (dom.length == undefined) {
this[0] = dom;
this.length++;
} else {
for (let i = 0; i < dom.length; i++) {
this[i] = dom[i];
this.length++;
}
}
}
jQuery.prototype.css = function (config) {
// console.log(config)
for (let i = 0; i < this.length; i++) {
// console.log(k)
for (let attr in config) {
// console.log(attr)
this[i].style[attr] = config[attr];
}
}
//jQ的精妙之处:循环\链式操作
return this;
}
jQuery.prototype.init.prototype = jQuery.prototype;
window.$ = window.jQuery = jQuery;
})()
$(".test")
.css({ color: "#ff0000" })
.css({ widht: "100px", height: "100px", bacgroundColor: "#0000ff" })
</script>
</html>