模拟jquery框架,实现.text() .html功能 代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="wrapper">hello jquery! ~~~ <b>你好啊~</b></div>
<script>
//作用域隔离
(function () {
window.jQuery = window.$ = jQuery;//将模拟的jq 挂载到window
function jQuery(id) {
return new jQuery.prototype.init(id);
}
var init=jQuery.prototype.init=function (id) {
this[0] = document.getElementById(id.slice(1));
this.length = 1;
return this;
}
jQuery.prototype.text = function (value) {
if (value) {
this[0].innerText = value;
return this;//链式操作的关键点 执行完 return 这个对象
} else {
return this[0].innerText;
}
};
jQuery.prototype.html = function (value) {
if (value) {
this[0].innerHTML = value;
return this;//链式操作的关键点 执行完 return 这个对象
} else {
return this[0].innerHTML;
}
};
init.prototype = jQuery.prototype;
})();
//模拟使用 jq 的text()
console.log($("#wrapper").text());
//模拟使用 jq 的html()
console.log($("#wrapper").html());
//试一试链式操作
$("#wrapper").html("<b>你好啊</b>").text("over");
</script>
</body>
</html>
1.如需转载本站原创文章,请务必注明文章出处并附上链接,非常感谢。
2.本站用于记录个人 工作、学习、生活,非商业网站,更多信息请 点击这里
上一篇: Object.assign()
下一篇: Vue双向绑定原理