Adobe AIR教程for HTML/JAVASCRIPT开发

最近想研究下Adobe Air ,发现网上的资源很少。以前在kalengo学的FLEX差不多都忘光了,这次想从HTML、JS方向来学学。网上看到这篇入门教程,便转过来放着。

第一步 — 安装Adobe AIR和Adobe AIR SDK

如果你还没装,可以去网站上下载Adobe AIR Runtime和Adobe AIR SDK.

装完Adobe AIR SDK以后,为了方便,你还需要把它的bin目录添加到系统的path变量下,这样你可以直接运行它的打包和debug工具。

第二步 — 创建一些目录

接下来创建一些目录来放置代码,比如:

/appname/
/appname/source/
/appname/source/icons/
/appname/build/

第三步 — 创建一个Application Descriptor

AIR需要一个Application Descriptor来描述它的内容和属性,这是一个XML格式的文件。

它的文件名是application.xml,放置在/appname/source/目录。

<application xmlns="http://ns.adobe.com/air/application/1.0">
  <id>com.example.appname </id>
  <version>1.0 </version>
  <filename>AppName </filename>
  <initialWindow>
    <content>index.html </content>
    <visible>true </visible>
    <width>600</width>
    <height>600</height>
  </initialWindow>
  <icon>
    <image16x16>icons/appname-16.png</image16x16>
    <image32x32>icons/appname-32.png</image32x32>
    <image48x48>icons/appname-48.png</image48x48>
    <image128x128>icons/appname-128.png</image128x128>
  </icon>
</application>

这个xml文件很有些复杂,也很有一些历史,最可恶的是AIR beta1到后来的beta2乃至最后的1.0,从来就没统一过,变了又变,所以我在网上找到的一些教程都失效了,只能针对早期的beta版使用。

关于它的详细内容,可以参考模板,在adobe sdk安装目录下的templates/descriptor-template.xml.

第四步 — 创建你的应用

下一步,创建一个index.html.

<html>
<head>
  <title>My Window Title</title>
</head>
<body>
  <h1>Hello World</h1>
</body>
</html>

如果需要添加css,javascript以及图片,可以在/appname/source/下创建子目录放进去,就像平常写web应用那样。

第五步 — 测试你的应用

如果你已经配置好了path环境变量(见第一步,需要重启电脑),下面很简单,首先打开一个命令行窗口,进入/appname/source/目录,然后运行:

adl application.xml

一切顺利的话,你的应用应该已经跑起来了,一个弹出的AIR应用窗口好不容易的展示它的第一次。

第六步 — 打包你的AIR应用

在很多磕磕碰碰,反复调试之后,你可能已经完成了应用,现在你准备向朋友或者网上的菜鸟炫耀一下你的处女作。那么我们开始打包,这一步其实比我想象的要简单。

首先需要生成一个签名Certificate,并放置在应用的根目录/appname/

adt -certificate -cn SelfSign -ou Dev -o “Example” -c US 2048-RSA cert.pfx 换成你的密码

然后就是进入source目录打包:

adt -package -storetype pkcs12 -keystore ../cert.pfx ../build/AirTest.air application.xml .

不出意外的话,会当场生成一个AppName.air文件,你可以安装一下感受亲手做的第一个Air应用。

原文:Adobe AIR Tutorial for HTML / JavaScript Developers

出处:http://www.ooso.net/archives/354 (Volcano )

HTML 5 Notifications api 桌面提醒接口

google chrome 浏览器支持html5 Notifications api ,用这个api 可以创建原生的提示信息,类似像OS X的Growl提示。

需要注意的是,您需要检查用户是否已提供您的站点许可来使用这个 API。如果没有,您必须请求许可,即是:需要用户手动按“允许”按钮。

完整实例:

<!DOCTYPE HTML>
<!-- http://dhtmlexamples.com/2011/01/28/creating-os-notifications-in-html5/ -->
<html>
<head>
    <title>Creating OS notifications in HTML5</title>
</head>
<body>

    <form>
        <input type="button" value="Hey, do you want to show notifications or not?" onclick="init();" />
        <input type="button" value="Send OS notification" onclick="notify();" />
    </form>

    <script type="text/javascript">
        const AUTO_CLOSE_DELAY_SECONDS = 5;

        function init() {
            if (window.webkitNotifications) {
                window.webkitNotifications.requestPermission();
            }
        }

        function notify() {
            var icon = "accept.png";
            var title = "[" + new Date().toLocaleTimeString() + "] This notification will close in " + AUTO_CLOSE_DELAY_SECONDS + " seconds";
            var body =  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus id magna ut sapien sodales ultricies eget nec metus. Pellentesque molestie nunc nec leo iaculis eu dictum ante porta. Sed adipiscing condimentum sapien a scelerisque. Quisque luctus elit vel odio semper iaculis. Nunc sit amet neque justo. Phasellus ullamcorper dui vel risus varius vitae aliquet purus consectetur. Fusce felis nibh, volutpat ac ornare at, ullamcorper eget lacus. Nunc euismod iaculis porta. In hac habitasse platea dictumst. Proin a sem sed neque tincidunt scelerisque eget in elit. Ut quis felis quis tortor sollicitudin sollicitudin id quis tortor. Nunc porttitor diam id leo lobortis aliquet. Nam scelerisque molestie dolor, placerat hendrerit urna euismod eu. Praesent nec massa enim. Donec nec urna dignissim nunc fringilla luctus. Nunc pretium urna et diam accumsan fermentum. Vivamus condimentum lectus vitae mi vulputate pulvinar. Curabitur adipiscing ultrices arcu. Vestibulum luctus malesuada erat sit amet rutrum. Nam feugiat lectus quis libero adipiscing laoreet.";

            if (window.webkitNotifications) {
                if (window.webkitNotifications.checkPermission() == 0) {
                    var popup = window.webkitNotifications.createNotification(icon, title, body);
                    popup.ondisplay = function(event) {
                        setTimeout(function() {
                            event.currentTarget.cancel();
                        }, AUTO_CLOSE_DELAY_SECONDS * 1000);;
                    }
                    popup.show();
                } else {
                    window.webkitNotifications.requestPermission();
                    return;
                }
            }
        }
    </script>

</body>
</html>

扩展参考:
http://slides.html5rocks.com/#notifications-api
http://www.chromium.org/developers/design-documents/desktop-notifications/api-specification
http://www.html5rocks.com/en/tutorials/notifications/quick/

jquery获取图片真实宽高

var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
    });

即将图片在内存里读取一遍即可。

apache 配置反向代理解决javascript ajax跨域问题

1、打开apache下的http.conf 文件。
找到

#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so

把前面的#去掉。(如果不开启这3个的话,ajax post 数据会出现http 500错误)

2、在http.conf文件末尾加上以下代码

ProxyRequests Off

<Proxy *>
Order deny,allow
Allow from all
</Proxy>

ProxyPass /foo/ http://foo.example.com/bar/
ProxyPassReverse /foo/ http://foo.example.com/bar/

说明 /foo/ 是本地服务器根目录下的foo文件夹。 这个文件夹映射到http://foo.example.com/bar/ 这里。

3、重启apache即可!

js就可以实现跨域post了。

$.post("http://localhost/foo/test.php")

实际是post到:http://foo.example.com/bar/test.php

相关参考网址:http://lamp.linux.gov.cn/Apache/ApacheMenu/mod/mod_proxy.html

http://shiningray.cn/proxypass-directive-in-apache.html

http://blog.csdn.net/paulluo0739/archive/2008/04/08/2260137.aspx

javascript传递日期参数给php date函数处理

php 使用 date 函数得出的长整型 和js 得出的长整型老是对不上。困扰了一上午,下午问archer,才把问题解决了。

php存储的时间截是到秒的,js存储的时间截是到毫秒,所以在js处理时,要除以1000。

多简单的一个问题啊,看来以后要多问问,免得浪费时间~~

给个参考:

// create a new javascript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds
var date = new Date(unix_timestamp*1000);;
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();

// will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes + ':' + seconds;

关键是 unix_timestamp*1000 这句。

php正常处理即可。

Google Javascript 编码风格指南

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

这条链接一直放在博客的回收站里,没发出来。今天无意发现,就干脆发出来吧。

换了工作,可能在一段时间里,都不会太深入的研究JS了,就当做是一种知识储备吧,毕竟学过的东西,以后用起来,上手也是很容易的。

Google的Javascript风格还是有很多地方值得学习的,收藏之~~以后用得上。

javascript 对象数组排序

javascript实现多维数组、对象数组排序,其实用的就是原生的sort()方法,用于对数组的元素进行排序。

其基本的用法就不说了,先看个简单的排序例子:

//Sort alphabetically and ascending:
var myarray=["Bob", "Bully", "Amy"]
myarray.sort() //Array now becomes ["Amy", "Bob", "Bully"]

数组直接调用sort()后,数组按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。

再来看看数字的排序:

//Sort numerically and ascending:
var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return a - b}) //Array now becomes [7, 8, 25, 41]

sort(fun)接受了个排序规则函数,这个函数将比较2个数字的大小。而我们的对象数组排序,实际上原理也是一样的。

对于对象数组排序,我们先写一个构造比较函数的函数:

//by函数接受一个成员名字符串做为参数
//并返回一个可以用来对包含该成员的对象数组进行排序的比较函数
var by = function(name){
	return function(o, p){
		var a, b;
		if (typeof o === "object" && typeof p === "object" && o && p) {
			a = o[name];
			b = p[name];
			if (a === b) {
				return 0;
			}
			if (typeof a === typeof b) {
				return a < b ? -1 : 1;
			}
			return typeof a < typeof b ? -1 : 1;
		}
		else {
			throw ("error");
		}
	}
}

要排序的数组:

var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}

直接调用函数:

employees.sort(by("age"));

到这里,对象数组排序就算基本实现了。那如何实现多个键值排序呢?意思就是先是对age排序,如果age相同,再比较name。

这时,我们可以进一步修改by函数,让其可以接受第二个参数,当主要的键值产生一个匹配的时候,另一个compare方法将被调用以决出高下。

//by函数接受一个成员名字符串和一个可选的次要比较函数做为参数
//并返回一个可以用来包含该成员的对象数组进行排序的比较函数
//当o[age] 和 p[age] 相等时,次要比较函数被用来决出高下
var by = function(name,minor){
	return function(o,p){
		var a,b;
		if(o && p && typeof o === 'object' && typeof p ==='object'){
			a = o[name];
			b = p[name];
			if(a === b){
				return typeof minor === 'function' ? minor(o,p):0;
			}
			if(typeof a === typeof b){
				return a <b ? -1:1;
			}
			return typeof a < typeof b ? -1 : 1;
		}else{
			thro("error");
		}
	}
}

employees.sort(by('age',by('name')));

好了,现在可以放心使用了。如果看不懂,可直接copy 这个by函数到你的应用里面,直接调用即可。

50个非常有用的javascript和jquery特效插件

这篇文章没做翻译,反正也凑合能看懂吧。大概看看图,需要的话点击进去看具体插件介绍。

个人感觉这50个插件,有部分还是很不错的。留下做个标记以后好找。呵呵~~

Colorful Sliders With jQuery & CSS3
In this tutorial we are using jQuery and the new transformation features brought by CSS3 to create a three dimensional dynamic slider effect. The techniques presented here – for creating sliders, and CSS dynamic resizable bars, can be used together or in part for powering all sorts of jQuery goodness.

JS-03 in 50 Useful JavaScript and jQuery Techniques and Plugins

Sponsor Flip Wall With jQuery & CSS
Designing and coding a sponsors page is part of the developer’s life (at least the lucky developer’s life, if it is about a personal site of theirs). It, however, follows different rules than those for the other pages of the site. You have to find a way to fit a lot of information and organize it clearly, so that the emphasis is put on your sponsors, and not on other elements of your design.

JS-39 in 50 Useful JavaScript and jQuery Techniques and Plugins

TipTip jQuery Plugin
TipTip detects the edges of the browser window and will make sure the tooltip stays within the current window size. As a result the tooltip will adjust itself to be displayed above, below, to the left or to the right of the element with TipTip applied to it, depending on what is necessary to stay within the browser window.
TipTip is a very lightweight and intelligent custom tooltip jQuery plugin. It uses ZERO images and is completely customizable via CSS.

JS-00 in 50 Useful JavaScript and jQuery Techniques and Plugins

Nivo Slider
The Most Awesome jQuery Image Slider

JS-02 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery.Syntax
jQuery.Syntax is an extremely fast and lightweight syntax highlighter. It has dynamic loading of syntax source files and integrates cleanly using CSS or modelines.

JS-04 in 50 Useful JavaScript and jQuery Techniques and Plugins

jquery.timepickr.js
This is my humble attempt to enhence web time picking.

JS-05 in 50 Useful JavaScript and jQuery Techniques and Plugins

Photo Zoom Out Effect with jQuery
Today we will show you how to create a simple image zoom out effect with jQuery. The idea is show some images which are zoomed in initially and when hovering over an image it gets zoomed out. This effect could be used in photography websites or image galleries. Our example uses some black and white images to focus on the effect.

JS-06 in 50 Useful JavaScript and jQuery Techniques and Plugins

A Fresh Bottom Slide Out Menu with jQuery
In this tutorial we will create a unique bottom slide out menu. This large menu will contain some title and a description of the menu item. It will slide out from the bottom revealing the description text and some icon. We will use some CSS3 properties for some nice shadow effects and jQuery for the interaction.

JS-07 in 50 Useful JavaScript and jQuery Techniques and Plugins

Making a Mosaic Slideshow With jQuery & CSS
Today we are making a jQuery & CSS mosaic gallery. Mosaic, because it will feature an interesting tile transition effect when moving from one slide to another.

JS-08 in 50 Useful JavaScript and jQuery Techniques and Plugins

17 jQuery Plugins for Easy and Efficient Reordering and Filtering Page Elements
Having full control of elements on a page and the order they are presented in can be quite useful. jQuery as always is a safe choice to go for. There are several good quality plugins to pick from. This post provides an overview of plugins you can use to provide simple yet powerful functionality to reorder, filter, add drag and drop capabilities etc.

JS-09 in 50 Useful JavaScript and jQuery Techniques and Plugins

Create an Impressive Content Editing System with jQuery and PHP
I’m going to show you how to use jQuery and PHP to build a content editing system that will allow you or your client to easily edit .html pages visually.

JS-10 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery MegaMenu Plugin

JS-11 in 50 Useful JavaScript and jQuery Techniques and Plugins

Excellent JQuery Plugins To Enhance Form Validation
Simple jquery plugins can enhance and beautify HTML form elements, these simple jquery scripts turn a simple HTML website to a fantastic look and feel. These plugins can be enabled very easily. In this roundup I have gathered most beautiful Jquery plugins that are related to all kinds of form validation. This list also includes roundups of some blogs. Go ahead and enjoy

gameQuery – a javascript game engine with jQuery
gameQuery is a jQuery plug-in to help make javascript game development easier by adding some simple game-related classes. It’s still in an early stage of development and may change a lot in future versions. The project has a Google Code page where the SVN repository of the project is hosted and a twitter page where you can follow the daily progress of the development.

JS-13 in 50 Useful JavaScript and jQuery Techniques and Plugins

Getting Buggy CSS Selectors to Work Cross-Browser via jQuery
Below I’ve prepared a simple table that describes a number of CSS selectors that are not cross-browser compatible, along with the jQuery syntax for each. The syntaxes are exactly the same as they would be in CSS, save for the jQuery wrapper (just remove $() and the quotes to get the CSS syntax), so using these selectors in jQuery will provide somewhat of a practice ground to prepare you for when they’re fully supported by all commonly-used browsers.

JS-14 in 50 Useful JavaScript and jQuery Techniques and Plugins

jqFancyTransitions: jQuery Image Rotator Plugin
jqFancyTransitions is easy-to-use jQuery plugin for displaying your photos as slideshow with fancy transition effects.

JS-15 in 50 Useful JavaScript and jQuery Techniques and Plugins

A demo of AD Gallery
A highly customizable gallery/showcase plugin for jQuery.

JS-16 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery UI Selectmenu: An ARIA-Accessible Plugin for Styling a Custom HTML Select Element
Our latest contribution to labs is the selectmenu plugin, which is designed to duplicate and extend the functionality of a native HTML select element, and lets you customize the look and feel, add icons, and create hierarchy within the options. Best of all, it’s built with progressive enhancement and accessibility in mind, has all the native mouse and keyboard controls, and is ThemeRoller-ready.

JS-17 in 50 Useful JavaScript and jQuery Techniques and Plugins

Create a Content Rich Tooltip with JSON and jQuery
Today we’re going to break the mold of the traditional tooltip. This tutorial will demonstrate how to build tooltips that are powered by jQuery, with information pulled from a JSON array.

JS-18 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery image zoom effect
So today I’m going to run through the technique used to zoom the image thumbnails and display the overlay of text.

JS-19 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery Roundabout Shapes
Roundabout Shapes provide even more paths along which your Roundabout can move. The current version of Roundabout Shapes offers eleven additional movements.

JS-20 in 50 Useful JavaScript and jQuery Techniques and Plugins

Extending jQuery’s selector capabilities

JS-21 in 50 Useful JavaScript and jQuery Techniques and Plugins

How to show/hide a hidden input form field using jQuery
This past week I was working on a project at work which included building a request form with multiple fields. It was a rather large form that included a dropdown list with an ‘other’ option. I wanted to allow users to select the ‘other’ option which then would show an input field so they can enter a specific description of what that ‘other’ item is. I didn’t want to clutter the form by displaying that additional field by default so I used a little jQuery, thus displaying it dynamically and only when needed.

JS-22 in 50 Useful JavaScript and jQuery Techniques and Plugins

A Better jQuery In-Field Label Plugin
This is a pretty nice effect, and it can really help to save space on forms. There are a billion different ways to implement this, and I don’t suggest you use the example from above because that was just a quick way to show the effect. So let’s walk through a couple of different implementation approaches and figure out the best way to implement this feature.

JS-24 in 50 Useful JavaScript and jQuery Techniques and Plugins

Useful JavaScript / jQuery Tools

JavaScriptMVC
JavaScriptMVC is an open-source framework containing the best ideas in enterprise JavaScript development. It guides you to successfully completed projects by promoting best practices, maintainability, and convention over configuration.

JS-26 in 50 Useful JavaScript and jQuery Techniques and Plugins

PEG.js – Parser Generator for JavaScript
PEG.js is a parser generator for JavaScript based on the parsing expression grammar formalism. It enables you to easily bulid fast parsers which process complex data or computer languages. You can use it as an underlying tool when writing various data processors, transformers, interpreters, or compilers.

JS-27 in 50 Useful JavaScript and jQuery Techniques and Plugins

PhoneGap
PhoneGap is an open source development tool for building fast, easy mobile apps with JavaScript.

JS-28 in 50 Useful JavaScript and jQuery Techniques and Plugins

JavaScript Shell
A command-line interface for JavaScript and DOM.

JS-29 in 50 Useful JavaScript and jQuery Techniques and Plugins

WireIt – a Javascript Wiring Library
WireIt is an open-source javascript library to create web wirable interfaces for dataflow applications, visual programming languages, graphical modeling, or graph editors.

JS-30 in 50 Useful JavaScript and jQuery Techniques and Plugins

JavaScript Programming Patterns
In this article I am trying to present some of the techniques out there that I have discovered. The patterns I would like to mention are the following:
– The Old-School Way
– Singleton
– Module Pattern
– Revealing Module Pattern
– Custom Objects
– Lazy Function Definition

JS-31 in 50 Useful JavaScript and jQuery Techniques and Plugins

Compare JavaScript frameworks
Modern Web sites and Web applications tend to rely quite heavily on client-side JavaScript to provide rich interactivity, particularly through the advent of asynchronous HTTP requests that do not require page refreshes to return data or responses from a server-side script or database system. In this article, you will discover how JavaScript frameworks make it easier and faster to create highly interactive and responsive Web sites and Web applications.

JS-32 in 50 Useful JavaScript and jQuery Techniques and Plugins

How to Test your JavaScript Code with QUnit
QUnit, developed by the jQuery team, is a great framework for unit testing your JavaScript. In this tutorial, I’ll introduce what QUnit specifically is, and why you should care about rigorously testing your code.

JS-33 in 50 Useful JavaScript and jQuery Techniques and Plugins

CoffeeScript
CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript’s less ostentatious kid brother — the same genes, roughly the same height, but a different sense of style. Apart from a handful of bonus goodies, statements in CoffeeScript correspond one-to-one with their equivalent in JavaScript, it’s just another way of saying it.

JS-34 in 50 Useful JavaScript and jQuery Techniques and Plugins

Mind-blowing JavaScript Experiments
The following JavaScript experiments demonstrates the amazing capabilities of the modern browsers such as Chrome and Safari. In this post I will showcase to you an array of experiments that will surely blows your mind off.

JS-35 in 50 Useful JavaScript and jQuery Techniques and Plugins

Online javascript beautifier
This little beautifier will reformat and reindent bookmarklets, ugly javascript, unpack scripts packed by the popular Dean Edward’s packer, as well as deobfuscate scripts processed by javascriptobfuscator.com.

JS-36 in 50 Useful JavaScript and jQuery Techniques and Plugins

CSS & Javascript Character Entity Calculator
Enter your HTML Entity Character number (such as &#2335 or just 2335 – ?) to get the CSS and JS values for that entity.

JS-37 in 50 Useful JavaScript and jQuery Techniques and Plugins

Dygraphs: Create interactive graphs from open source Javascript library
Dygraphs is an open source JavaScript library that produces an interactive, zoom-able charts of the present time series. It is mainly designed to display the dense data sets and enable the users to explore and interpret them. It is a JavaScript Visualization Library.

JS-38 in 50 Useful JavaScript and jQuery Techniques and Plugins

Showdown – Markdown in JavaScript
Showdown – a JavaScript port of Markdown

JS-40 in 50 Useful JavaScript and jQuery Techniques and Plugins

Copy to Clipboard with ZeroClipboard, Flash 10 and jQuery
With today’s post I will show you a contrived example to get you started. I eventually hope to add this to the contextMenu.js jQuery plugin that I use, but for now this should be pretty straight forward. I do want to note that in the demo and download I am loading the latest version of the jQuery library (1.3.1) from Google’s CDN for the first time in any of my posts. For more information on how to do this see the instructions from Google.

JS-41 in 50 Useful JavaScript and jQuery Techniques and Plugins

fLABjs
fLABjs is a special API wrapper around LABjs which adapts the code to work properly in a file:// local filesystem environment. There are a number of things with core LABjs does which are not appropriate for local filesystems, such as XHR, special path handling rules, etc.

JS-43 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery LazyLoad Ad : Delays loading of advertising
jQuery LazyLoad Ad is a jQuery plugin that takes advantage of LazyLoad delaying ads loading.

qTip – The jQuery tooltip plugin
qTip is a tooltip plugin for the jQuery framework. It’s cross-browser, customizable and packed full of features!

JS-47 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery Collapsing and Expanding Table Rows

JS-48 in 50 Useful JavaScript and jQuery Techniques and Plugins

Improving Search Boxes with jQuery
This time we will learn how to improve a little more our sites by adding some additional interactions to our search boxes like autofocus, highlighting, autoreplace default text and more by using jQuery.

JS-49 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery Grid Plugin

JS-50 in 50 Useful JavaScript and jQuery Techniques and Plugins

Pines Notify jQuery Plugin
Pines Notify’s features include:
– Timed hiding with visual effects.
– Sticky (no automatic hiding) notices.
– Optional hide button.
– Supports dynamically updating text, title, icon, type…
– Stacks allow notice sets to stack independently.
– Control stack direction and push to top or bottom.

JS-51 in 50 Useful JavaScript and jQuery Techniques and Plugins

jQuery Slider plugin (Safari style)
jQuery Slider is easy to use and multifunctional jQuery plugin.

JS-52 in 50 Useful JavaScript and jQuery Techniques and Plugins

原文转自:http://www.noupe.com/javascript/50-useful-javascript-and-jquery-techniques-and-plugins.html

JavaScript单元测试框架介绍

  • FireUnit

介绍:这个是John Resig另起炉灶做的,在他的博客John Resig – FireUnit: JavaScript Unit Testing Extension,发布了他与Jan Odvarko合作开发的基于Firebug的扩展FireUnit。
简单说来,FireUnit给Firebug增加了一个标签面板,并提供了一些简单的JavaScript API来记录和查看测试。参考:http://shawphy.com/2008/12/fireunit.html
评价:FireUnit在易用性上表现非常出众,非常适合基于Firebug做调试环境的前端工程师。

  • QUnit

介绍:QUnit 是一款强大而且容易使用的JavaScript 测试框架,它被用于jQuery 与其插件的测试,同时它也同样可以测试普通的JavaScript 代码。参考:http://net.tutsplus.com/tutorials/javascript-ajax/how-to-test-your-javascript-code-with-qunit/

评价:QUnit是一款易用的,基于jQuery的测试框架,如果项目中用到jquery,推荐用QUnit做单元测试。

  • jsUnit

介绍:系统化的解决方案,基于XNuit规范,如果你会使用jUnit、NUnit等框架,对这个应该会很容易上手,且包括服务器端(Java的)。参考:http://www.jsunit.net/

评价:非常全面,专业,适合大型企业级开发。

  • Test.Simple & Test.More

介绍:这个是jQuery之父John Resig在他的著作《Pro Javascript》中推荐的测试框架

参考:http://openjsan.org/doc/t/th/theory/Test/Simple/0.21/lib/Test/Simple.html
评价:非常容易上手,非常简洁,适合中小型项目快速引入单元测试。

总结:推荐使用Qunit和FireUnit。

JavaScript的constructor属性与typeof函数的区别

有时你可能需要对变量进行类型检查,或者判断变量是否已定义。有两种方法可以使用:typeof函数与constructor属性

typeof函数的用法可能不用我多说,大家都知道怎么用。而constructor属性大家可能就陌生点。在《精通JavaScript》与《JavaScript 语言精粹》里都有提到construct的用法,但我用自己的几个浏览器(IE7.0 / Firefox3.6.8 / Opera)测试的结果却和书上说的不一样。但是仍然是有办法通过constructor属性来检查变量类型的。

这里先补充一下,为什么明明有typeof函数可以很方便地用来检测类型,还要用constructor呢?

因为typeof会把所有的数组类型以及用户自定义类型判断为object,从而无法知道更确切的信息。而constructor却可以解决这个问题。

ok,明白了我们为什么要用constructor,现在让我带大家一步步认识一下typeof和constructor用法之间的差异吧~

首先我们运行一下下面这段代码:
1 var i;
2 alert(typeof(i));  //”undefined”
3 alert(i.constructor); //error

这3行代码告诉你什么情况下可以用constructor。

你可以看到第2行返回了字符串’undefined’,而第三行则发生了错误,原因是i变量还没有类型定义,自然也没有constructor的存在。

从这一点上看,typeof可以检查到变量是否有定义,而construct只能检查已定义变量的类型。

再运行一下下面这段代码:
1 var i = 2;
2 alert(typeof(i)); //”number”
3 alert(i.constructor); //
4 alert(typeof(i.constructor)); //”function”
 
你会看到第2行返回了字符串’number’,第3行返回了一串类似函数定义的代码字符串(这就是跟《精通JavaScript》一书中介绍的不一样的地方)。

我们再用typeof检查一下constructor到底是个什么样类型的属性,第4行返回结果’function’,也就是说,实际上constructor是一个函数,更确切地说是一个构造函数。这时你就可以知道,为什么constructor可以检查出各种类型了。

有经验的程序员看到这里应该知道要怎么利用constructor来检查变量类型了。方法有多种,这里提供一种比较容易理解的方法。

其实想法很简单,就是把construcor转化为字符串,通过寻找匹配字符串(function名)来确定是否指定类型。如下例子:
1 function user() {};
2 var i = new user();
3 alert((i.constructor+”).match(/user/) == null);
 
这仅仅是个简单的例子。如果返回true则变量i不是user类型,返回false则变量是user类型。

当然,这样检测是不够精确的,比如其实他是一个myuser类型的时候,同样会被认为是user类。所以你需要书写更精确的正则表达式去进行匹配。

可以这样简单改进你的正则表达式:
/function user\(\)/
替换上面代码段中的/user/。当然,如果你的构造函数原型是user(a),那么应该这样书写你的正则表达式:
/function user\(a\)/
 
到这里你应该知道怎样使用constructor类型去检查变量类型了吧?

ok,最后再提个醒,如果你要用基于constructor的方法去检查一些基本类型,如

Object / Array / Function / String / Number / Boolean

在你的正则表达式中,一定要将这些单词的首字母大写!!而如果该类型是自定义类型,则根据你定义的时候标识符的写法确定。

最后再给个官方例子:

<script type="text/javascript">
var test=new Date()
if (test.constructor==Array)
{document.write("This is an Array")}
if (test.constructor==Boolean)
{document.write("This is a Boolean")}
if (test.constructor==Date)
{document.write("This is a Date")}
if (test.constructor==String)
{document.write("This is a String")}
</script>
输出在结果:
This is a Date