js中的写出想jquery中的函数一样调用

时间:2023-12-28 19:44:32

1.IIFE:

  Immediately-Invoked function Expression 函数模块自调用

2.代码实现

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<div id="demo">的么的事</div>
</head>
<body>
<script>
(function () {
document.write("好啊好啊");
})(); //定义$
(window.$=function (args) {
//定义val
function val() {
return getElem().innerHTML;
}
function getElem() {
if(args!=null){
if(args.indexOf("#")==0){
return document.getElementById(args.substring(args.indexOf("#")+1,args.length));
}
}
}
return {
val:val
}
})();
document.write($("#demo").val());
</script>
</body>
</html>