(function(){})(jQuery)
(function($){})(jQuery)常在开发插件时使用,与jQuery(function(){})不同,(function($){})(jQuery)相当于一个匿名函数,在DOM节点加载完成时就已开始执行,所以在效率上要比jQuery(function(){})高。
$.fn.method()
$.fn.method()是把方法扩展到了对象的prototype上,所以实例化一个jQuery对象的时候,它就具有了这些方法。
示例
test.js
(function($){
$.fn.testsetting = function(options){
var setting = $.extend({
settingCss: {
background : "green",
width : ‘200px‘,
height : ‘300px‘
},
dtCss :{
width:‘30px‘,
height: ‘100px‘,
background : "red"
},
theme:‘testbody‘
},options);
return this.each(function(){
var target = $(this);
var testdiv = $(‘#testdiv‘);
var dt = $(testdiv).find(‘div‘);
dt.css(setting.dtCss);
target.addClass(setting.theme);
testdiv.css(setting.settingCss);
$(dt).mouseenter(function(){
if($(testdiv).hasClass(‘divbg‘)){
return
}
$(testdiv).addClass(‘divbg‘)
});
$(Window).click(function (e) {
if ($(e.target).closest(dt).length) {
return;
}
$(testdiv).removeClass("divbg");
});
});
}
})(jQuery)
test.html
<!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>
<!--jQuery-->
<script src="https://blog-static.cnblogs.com/files/PoetryAndYou/jquery.min.js"></script>
<link rel="stylesheet" href="test.css">
<script src="test.js"></script>
</head>
<body>
<div class = "test">
<div id = "testdiv">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
</div>
</body>
<script>
$(‘.test‘).testsetting(
{
settingCss: {
background : "cornflowerblue",
width : ‘200px‘,
height : ‘300px‘
},
dtCss :{
width:‘30px‘,
background : "red",
height: ‘100px‘
},
theme:‘testbody‘
}
);
</script>
</html>
test.css
.testbody{
background-color: aqua;
width: 300px;
}
.testbody01{
background-color: red;
width: 300px;
}
.divbg{
background-color: cadetblue!important;
}