This weird piece of code I always see in Javascript
I'm not Javascript expert, but the old Javascript I know is just a bunch of simple functions and variables like this:
function doSomething(){
var data = "test";
return data;
}
But lately I'm seeing some Javascript code like this:
开发者_如何学编程$(document).ready(function(){
$("#about").hide();
$(".tababout").collapser({
target: '#about',
effect: 'slide',
changeText: false,
});
});
What the hell is this? What is it called? Is it easier and supported by all browsers? I need more informations about this please.
What you're looking at is jQuery. It's an external library but it supports most (if not all) browsers. You need to download it and include it with your project if you were to use it though, see Downloading jQuery for that.
It's just plain old javascript:
var $ = function(sel) {
return new init(sel);
};
function init(sel) {
if (sel.nodeName) {
this[0] = sel;
this.length = 1;
} else {
var elems = document.querySelectorAll(sel);
for (var i = 0; i < elems.length; i++) {
this[i] = elems[i];
}
this.length = elems.length;
}
return this;
};
init.prototype.ready = function(fn) {
_ready(fn);
return this;
};
function _ready(fn) {
if (!document.body) {
setTimeout(function(){_ready(fn);}, 0);
} else {
fn();
}
}
init.prototype.hide = function() {
this.each(function() {
this.style.display = 'none';
});
return this;
};
init.prototype.show = function() {
this.each(function() {
this.style.display = 'block';
});
return this;
};
init.prototype.each = function(fn) {
for (var i = 0; i < this.length; i++) {
fn.call(this[i], i, this[i]);
}
return this;
};
$("#about").hide().each(function(i,el) {
setTimeout( function(){$(el).show()}, 2000 );
});
DEMO: http://jsfiddle.net/JGWUs/3/
精彩评论