/* console.dir( jQuery('#selector a.jt:eq(0)').data('events') ); jQuery.each($('#selector a.jt:eq(0)').data('events'), function(i, event){ jQuery.each(event, function(i, handler){ console.log( handler.toString() ); }); }); */ //console.log(eval('1+1')) console.time('function_name') for(var i=0;i<100000;i++){} console.timeEnd('function_name')
Firebug对于Web开发人员来说,已经成为了不可或缺的工具,但是在我日常的工作中,常常感觉还没有能够深刻的挖掘出她的潜力,今天花了点时间仔细研究了Console和命令行的使用在提高工作效率方面的作用,
记下来和大家分享一下.
Firebug一共有Console,HTML,CSS,Script,DOM,NET六个Tab,今天着重说一下Console的用法。
其实我们对于Console应该非常熟悉,因为这里是Firebug给出各种信息的窗口,而这也正是Console的主要用途,日志记录(Logging)。
除此之外,Console还提供了通过命令行方式来调试Javascript的方法。下面就来学习一下Console的用法。
1、Firefox的日志记录(Logging in Firefox)。
通过Console的记录方法,我们可以不再使用烦人的alert或者document.write方法来进行调试。
Firebug提供了五种日志的类型:
console.log:记录一行信息,无任何图标提示;
console.debug:记录一行信息,带超链接,可以链接到语句调用的地方;
console.error():向控制台中写入错误信息,带错误图标显示和高亮代码链接;
console.info():向控制台中写入提示信息,带信息图标显示和高亮代码链接;
console.warn():向控制台中写入警告信息,带警告图标显示和高亮代码链接;
consle打印字符串支持字符串替换,使用起来就像c里面的printf(“%s",a),支持的类型包括:
%s string,字符串
%d,%i 整型
%f 浮点
%o 对象
如果使用%o的话,对象就会用绿色的超链接表示出来,单击后会将你带到DOM视图。
2、分组(Grouping)。
如果某一类的信息特别多时,分组就有利于逻辑的划分。
使用上很简单,参见代码。
function consoleGroup(){
var groupname = "Group 1";
console.group("Message group %s", groupname);
console.log("This is the 1 message in %s", groupname);
console.log("This is the 2 message in %s", groupname);
console.log("This is the 3 message in %s", groupname);
console.groupEnd();
goupname = "Group 2";
console.group("Message group %s", goupname);
console.log("This is the 1 message in %s", goupname);
var subgroupname = "Sub group 1";
console.group("Message group %s",subgroupname);
console.log("This is the 1 message in %s", subgroupname);
console.log("This is the 2 message in %s", subgroupname);
console.log("This is the 3 message in %s", subgroupname);
console.groupEnd();
console.log("This is the 2 message in %s", goupname);
console.groupEnd();
}
3、console.dir和console.dirxml
console.dir可以将一个对象的所有方法和属性打印出来,这个方法无疑是非常有用的,我们不再需要object.toString这样的方法支持了,只要有firebug,查看对象也变得很轻松同时,我们也可以将页面中的元素作为一个对象打印出来,但是你要小心,因为这将输出众多的信息,可能你会迷失在繁杂的信息中而找不到自己需要的条目。我们可以通过分组将这些大量的信息放入一个分组中,这样可以在逻辑上更清楚一些。
function consoleDir(){
function Car(){
this.Model = "Old Model";
this.getManu = function(){
return "Toyota";
}
}
var objCar = new Car();
console.dir(objCar);
console.dir(zoo);
var groupname = "Css Style";
console.group("The button Style", groupname);
console.dir(document.getElementById('consoledir').style, groupname);
console.groupEnd();
}
console.dirxml 打印出HTML元素的XML表示形式.
网页制作poluoluo文章简介:Firebug一共有Console,HTML,CSS,Script,DOM,NET六个Tab,今天着重说一下Console的用法。
3、console.dir和console.dirxml
console.dir可以将一个对象的所有方法和属性打印出来,这个方法无疑是非常有用的,我们不再需要object.toString这样的方法支持了,只要有firebug,查看对象也变得很轻松同时,我们也可以将页面中的元素作为一个对象打印出来,但是你要小心,因为这将输出众多的信息,可能你会迷失在繁杂的信息中而找不到自己需要的条目。我们可以通过分组将这些大量的信息放入一个分组中,这样可以在逻辑上更清楚一些。
function consoleDir(){
function Car(){
this.Model = "Old Model";
this.getManu = function(){
return "Toyota";
}
}
var objCar = new Car();
console.dir(objCar);
console.dir(zoo);
var groupname = "Css Style";
console.group("The button Style", groupname);
console.dir(document.getElementById('consoledir').style, groupname);
console.groupEnd();
}
console.dirxml 打印出HTML元素的XML表示形式.
4、断言(console.assert())。
console.assert()可以用来判断一个表达式是否正确,如果错误,他就会打印错误信息在控制台窗口中。
5、追踪(console.trace())。
console.trace()是一个非常有趣的功能。我们先来看看官方的解释:打印Javascript执行时刻的堆栈追踪。
这个函数可以打印出程序执行时从起点到终点的路径信息。
比如如果我们想知道某个函数是何时和如何被执行的,我们将console.trace()放在这个函数中,我们就能够的看到这个函数被执行的路径。
这个函数在调试其他人的源代码时非常有用。
6、计时(Timing)。
console.time(timeName)可以用来计时,这个在我们需要知道代码执行效率的时候特别有用,就不用自己造轮子了。
function consoleTime(){
var timeName = "timer1";
console.time(timeName);
var a = 0;
for(var i = 0; i < 100; i++){
for(var j = 0; j < 100; j++){
// console.log('Hello world');
a = a + 1;
}
}
console.log("a = %d", a);
console.timeEnd(timeName);
}
网页制作poluoluo文章简介:Firebug一共有Console,HTML,CSS,Script,DOM,NET六个Tab,今天着重说一下Console的用法。
7、Javascript分析器(Javascript Profiler)。
我们可以通过代码console.profile('profileName')或者单击Profiler标签来进行Javascript代码执行的分析。这个功能有点类似于console.time(),可以帮助我们评估代码的表现,但是能够提供比console.time()更详细的信息。
有三种方法可以调用Javascript profiler。一种是在代码中写入分析脚本,一种是单击profile标签,最后还可以在命令行下输入命令来执行。
执行后,可以看到详细的输出结果,下面对各项进行一些说明:
Function Column:显示调用的函数名称;
Call Column:显示调用次数;
Percent Column:显示消耗的时间比;
Own Time:显示函数内部语句执行的时间,不包括调用其他函数的时间;
Time Column:显示函数从开始到结束的执行时间;
Avg Column:平均时间。Avg = Own / Call;
Min & Max Column:显示最小和最大时间;
File Column:函数所在的文件;
8、其他的一些选项。
在Console Tab的最右侧有一个Options的选项,在这里可以自己定义需要显示的错误,其内容很好理解,这里就不多说了。有一点就是Firebug1.3以后,多了Show Chrome Errors、Show Chrome Message等几个选项,这几个选项还没有验证过其具体的作用,哪位知道的可以共享一下。
[参考资料]
Firebug Tutorial
http://michaelsync.net/2007/09/09/firebug-tutorial-logging-profiling-and-commandline-part-i
Firebug Tutorial
http://michaelsync.net/2007/09/10/firebug-tutorial-logging-profiling-and-commandline-part-ii
/**************************************************************************************/
http://james.padolsey.com/javascript/things-you-may-not-know-about-jquery/
I was going to do a bit of a series, releasing a jQuery tip every day or week or something, but I think I’m a little too lazy to commit to something like that. So I’ve compiled them all into one post! I’ll probably add to the list at later dates so make sure to bookmark it!
Do you have a tip nobody knows about? – Add it in the comments…
$.fn
is just a shortcut tojQuery.prototype
.- You can test if a jQuery collection contains any elements by trying to access the first element, e.g.
if($(selector)[0]){...}
. - jQuery normalizes the event object across all browsers! Have a look at all the available properties/methods over here: http://docs.jquery.com/Events/jQuery.Event.
- When you create a plugin you have access to the jQuery chain’s previous object:
jQuery.fn.doSomething = function() { this; // => $('a') this.prevObject; // => $('li') // Remember chaining in your plugins: return this; }; jQuery('li').show() .find('a').doSomething(); // You could even create a new 'root' plugin: // (Returns the 'root' of a chain) jQuery.fn.root = function() { // Root is always document so we have to // go back to one before the last: var root = this; while(root.prevObject.prevObject) { root = root.prevObject; } return root; }; $('li').find('a').children().root(); // <= $('li') is returned // Using root() is the same as using end().end() in this situation
- You can namespace events! This is especially useful for plugin development:
jQuery.fn.myPlugin = function() { // Clean up after yourself! jQuery.myPlugin = { cleanUp: function() { // Remove all click handlers binded // as a result of the plugin: jQuery('*').unbind('click.myPlugin'); // ALternatively, remove ALL events: jQuery('*').unbind('.myPlugin'); } }; return this.bind('click.myPlugin', function() { // Do something... }); }; // Note, you can also namespace data: // E.g. $(elem).data('whatever.myPlugin',value);
- You can access all event handlers bound to an element (or any object) through jQuery’s event storage:
// List bound events: console.dir( jQuery('#elem').data('events') ); // Log ALL handlers for ALL events: jQuery.each($('#elem').data('events'), function(i, event){ jQuery.each(event, function(i, handler){ console.log( handler.toString() ); }); }); // You can see the actual functions which will occur // on certain events; great for debugging!
- jQuery natively supports JSONP (‘JSON with padding’) which effectively means you can make cross-domain "Ajax" requests (although not strictly Ajax since it doesn’t use XHR). For this to work the requested domain must have some JSONP API in place (it must be able wrap the JSON with a specified callback function). An example:
function getLatestFlickrPics(tag,callback) { var flickrFeed = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=' + tag + '&tagmode=any&format=json&jsoncallback=?'; jQuery.getJSON(flickrFeed, callback); } // Usage: getLatestFlickrPics('ferrari', function(data){ jQuery.each(data.items, function(i, item){ $("<img/>").attr("src", item.media.m).appendTo('body'); }); });
- You might find it a little messy but jQuery enables us to create an entire DOM structure within a single chain:
// Create and inject in one chain: jQuery('<div/>') .append('<p><a href="#">Foo</a></p>') .find('p a') .click(function(){ // Do something... return false; }) .end() .append('<p><a href="#">Bar</a></p>') .find('p:eq(1) a') .click(function(){ // Do something else... return false; }) .end() .appendTo('body');
- Accessing the DOM elements within a jQuery collection is incredibly easy:
var HTMLCollection = $('div').get(); // Alternatively, if you only want the first element: $('div').get(0); $('div').get()[0]; $('div')[0];
- Not only can you bind events to DOM elements; you can also bind a custom event to ANY object!
function Widget() { // Do something... }; var myPhotoWidget = new Widget('photos'); jQuery(myPhotoWidget).bind('photoAdd', function() { // Custom event handling... }); // Trigger event: jQuery(myPhotoWidget).trigger('photoAdd');
- Finding the index of a selected element is very easy. jQuery gives us the ‘index’ method:
$('table tr').click(function(){ // Find index of clicked table row: var index = $('table tr').index(this); });
- You can create your own filter selectors. I did a post on this a while back, but take a look at an example anyway:
$.expr[':'].external = function(elem,index,match) { var url = elem.href || elem.src, loc = window.location; return !!url.match(new RegExp('^' + loc.protocol + '//' + '(?!' + loc.hostname + ')' )); }; // You can now use it within your selectors: // Find all external anchors: $('a:external'); // Find all external script elements: $('script:external'); // Determine if link is external: $('a#mylink').is(':external'); // true/false
- I see quite a lot of people still using JavaScript’s FOR or WHILE constructs to create loops in their jQuery scripts. There’s nothing wrong with this but be aware that jQuery’s ‘each’ method can also iterate over arrays and objects!
var myArr = ['apple','banana','orange']; $.each(myArr, function(index, item) { // Do something with 'item' // return false to BREAK // return true to CONTINUE });
- The ‘filter’ method accepts a String selector or a function. When using it with a function you must return false to remove the element from the stack and true to keep it:
$('div').filter(function(){ return this.childNodes.length > 10; // Must return a Boolean });
- You don’t have to give new elements IDs or classes to reference them later, just cache them into a variable:
var myInjectedDiv = $('<div/>').appendTo('body'); // Use 'myInjectedDiv' to reference the element: myInjectedDiv.bind('click', function(){ // ... });
- jQuery’s ‘map’ method is incredibly useful, the passed function will be run on every item of the passed array (or object) and whatever the function returns each time is added to the new array, take a look:
// Create an array containing all anchor HREF attributes: var URLs = $.map($('a'), function(elem, index){ return elem.href; }); // URLs = ['http://google.com', 'http://whatever.com', 'http://yahoo.com']
- This isn’t jQuery related but it can be very useful. When you need to compare two different ways of doing something (performance-wise) you can use the Firebug console to log the time taken to complete a chunk of code, for example:
console.time('My first method'); // Do something... console.timeEnd('My first method'); console.time('My second method'); // Do something else... console.timeEnd('My second method'); // Firebug will log the time (in milliseconds) taken // to complete each chunk...