1,基本格式对比
jQuery拿到页面数据的固定格式
$(document).ready(function(){
});
原生JS的固定格式
window.onload=function(ev){
}
2,入口函数对比
(1)拿到dom元素(img),在浏览器端F12的Console打印出效果
$(document).ready(function(){
//拿到在jsp页面写的代码,在Console显示(能拿到)
var img = $("img")[0];
console.log(img);
//拿到图片的宽度,在Console显示(结果是不能拿到)
var width = $(img).width;
console.log(width);
});
window.onload=function(ev){
//拿到在jsp页面写的代码,在Console显示(能拿到)
var img = document.getElementByTagName("img")[0];
console.log(img);
//拿到图片的宽度,在Console显示(能拿到)
var width = window.getComputedStyle(img).width;
console.log(width);
}
<body>
<img ... ...>
</body>
总结:原生的JS会等到图片加载完再执行,jQuery不会
(2)jQuery编写多个入口函数,后面的不会覆盖前面的
3,jQuery入口函数的四种写法
第一种
$(document).ready(function(){
alert("hello jQuery");
});
第二种
jQuery(document).ready(function(){
alert("hello jQuery");
});
第三种(开发中推荐使用第三种)
$(function(){
alert("hello jQuery");
});
第四种
jQuery(function(){
alert("hello jQuery");
});
4,访问符冲突问题
(1),释放$使用权
jQuery.noConflict();
释放必须在编写其它jQuery代码之前,释放之后不能使用$,改为使用jQuery
jQuery(function(){
alert("hello jQuery");
});
(2),自定义访问符
var nb = jQuery.noConflict();
nb(function(){
alert("hello jQuery");
});
5,jQuery核心函数
$();/jQuery();就代表调用jQuery核心函数
(1),接收一个函数
$(function(){
alert("hello jQuery");
});
(2),接收一个字符串
(2.1),接收一个字符串选择器
var box1= $(".box1");
var box1= $(".box2");
console.log(box1);
console.log(box2);
(2.2),接收一个代码片段,并创建代码片段对应的元素
var p = $("<p>我是段落</p>");
console.log($p);
$box1.append($p);
(3),接收一个DOM元素(会包装成一个jQuery返回给我们)
var span = document.getElementByTagName("span")[0];
console.log(span );
var span1 = $(span);
console.log(span1 );
<body>
<div class="box1"></div>
<div id="box2"></div>
<span>我是span</span>
</body>
6,jQuery对象
jQuery,对象是一个伪数组(有0到length-1的属性,并且有length属性)
var $div = $("div");
console.log($div );
<body>
<div>div1</div>
<div>div2</div>
<div>div3</div>
</body>
7,静态方法和实例方法
(1),定义一个类
function AClass(){
}
(2),给这个类添加静态方法(直接添加给类的就是静态方法)
AClass.staticMethod = function(){
alert("staticMethod");
}
静态方法的调用
AClass.staticMethod();
(3),添加一个实例方法(实例方法通过类的实例调用)
AClass.prototype.instanceMethod = function (){
alert("instanceMethod");
}
创建一个实例对象
var a = new AClass();
通过实例调用实例方法
a.instanceMethod();