<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js封装</title>
</head>
<body>
<div>aaa</div>
<div>bbb</div>
<div>ccc</div>
<span class="ddd">ddd</span>
<span id="eee">eee</span>
<script>
(function (window) {
function jQuery (selector) {
return new jQuery.fn.init(selector)
}
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function(selector) {
let elements = document.querySelectorAll(selector)
for (let i = 0; i<elements.length; i++){
this[i] = elements[i]
}
this.length = elements.length
}
}
jQuery.fn.init.prototype = jQuery.fn
jQuery.fn.extend = jQuery.extend = function (...args) {
let target = [], source = [...args]
if (args.length === 1) {
target = this
} else {
target = args[0]
source.splice(0,1)
}
Object.assign(target, ...source)
return target
}
// 添加工具类方法
jQuery.extend({
each () {
console.log('each方法')
}
})
// 添加DOM类方法
jQuery.fn.extend({
css (name,value) {
for (let i = 0; i < this.length; i++) {
this[i].style[name] = value
}
},
attr () {
console.log('attr方法')
}
})
window.$ = window.jQuery = jQuery
})(window)
let p = {}
$.extend(p, {a: 1},{b:2})
$.fn.extend({
getDate () {}
})
$.each()
$('div').css('color', 'red')
$('div').attr()
</script>
</body>
</html>