Wednesday, October 29, 2008

Tapestry5 Page ActionLink 拼装过程

Page.createActionLink ->
LinkFactory.createActionLink ->
InvocationTarget.getPath ->
Link

其中在InvocationTarget的实现类ActionLinkTarget.getPath方法内实际拼装path,path中包括page, component, event等,如test.username:autocomplete。在LinkFactory中调用Link.addParameter方法将page activation context追加到link中。

Java produce md5 and sha1

import org.apache.commons.codec.digest.DigestUtils;

public class Test {

public static void main(String[] args) {
System.out.println(DigestUtils.md5Hex("data"));
System.out.println(DigestUtils.shaHex("data"));
}

}

Monday, October 27, 2008

Java in a nutshell 泛型学习笔记

泛型的类型变量只可以作用于该类中的实例成员,而不可以用于静态成员。但是,跟实例方法一样,静态方法也可以使用通配符,不过无法使用所处泛型类的泛型实例变量,但可以声明自己的类型变量。当一个方法(不管是实例方法还是静态方法)只要明它自己的类型变量,这个方法就是一个泛型方法(generic method)。

import java.util.ArrayList;
import java.util.List;

public class Tree<V> {

V value;

List<Tree<? extends V>> branches = new ArrayList<Tree<? extends V>>();

public Tree(V value) {
this.value = value;
}

V getValue() {
return this.value;
}

void setValue(V value) {
this.value = value;
}

int getNumBranches() {
return this.branches.size();
}

Tree<? extends V> getBranch(int n) {
return branches.get(n);
}

void addBranch(Tree<V> branch) {
branches.add(branch);
}

// public static <N extends V> V sum(Tree<N> t) {}
// can not make a static reference to the non-static type V
// 静态方法无法使用它们所在类的类型变量,但它们可以声明自己的类型变量
// 静态成员不能使用泛型的类型变量
// 这个不是 generic method
public static double sum(Tree<? extends Number> t) {
double total = t.value.doubleValue();
for (Tree<? extends Number> b : t.branches)
total += sum(b);
return total;
}

// 当类型变量是用来表示两个参数或一个参数与一个返回值之间的关系时,就需要使用到generic method
// 在方法返回值前面先声明自己的类型变量,如下的N。
public static <N extends Number> Tree<N> max(Tree<N> t, Tree<N> u) {
double ts = sum(t);
double us = sum(u);
if (ts > us)
return t;
else
return u;
}

public static void main(String[] args) {
Tree<String> s1 = new Tree<String>("Tree");
Tree<String> s2 = new Tree<String>("Tree");
Tree<? extends Number> i1 = new Tree<Integer>(3);
Tree<? extends Number> i2 = new Tree<Integer>(3);
s1.addBranch(s2);
// i1.addBranch(i2); // compile error.
System.out.println(i1.getValue());
System.out.println(s1.getValue());
System.out.println(i1.getNumBranches());
System.out.println(s1.getNumBranches());
}
}

Ajax in Tapestry5

在Tapestry5中使用一些简单的ajax还是比较方便的,ajax返回结果可以是JSONObject/JSONArray/Component/Block/String/ResponseStream等,可设置zone组件中的show/update这二个自定义的javascript方法实现复杂效果。

返回的Block和Component是以JSON对象形式返回,其中key必须为"content",value即为要渲染的内容,这是用Zone组件更新页面的最基本用法。也可以将ResponseStream以"application/json"形式返回客户端,见下面例子。

Component是指org.apache.tapestry5.runtime.Component对象,可以通过ComponentSource.getPage()或者ComponentSource.getComponent()方法获取。
具体使用方法见以下例子:

import java.util.Date;
import org.apache.tapestry5.Block;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanDisplay;
import org.apache.tapestry5.internal.services.ClientBehaviorSupport;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.runtime.Component;
import org.apache.tapestry5.services.ComponentSource;
import org.apache.tapestry5.util.TextStreamResponse;

public class Test {

@Environmental
private ClientBehaviorSupport clientBehaviorSupport;

@Inject
@Property
private Block block;

@Inject
private ComponentSource componentSource;

@InjectComponent
private BeanDisplay beanDisplay;

@BeginRender
void begin() {
// clientBehaviorSupport.addZone("link1", "show", "update");
clientBehaviorSupport.linkZone("link1", "zone1");
}

StreamResponse onActionFromLink1() {
StreamResponse response = new TextStreamResponse("application/json", "{\"content\":\"更新zone1中原来的内容\"}");
return response;
}

JSONObject onActionFromLink2() {
return new JSONObject().put("content", "update zone2.");
}

Block onActionFromLink3() {
return block;
}

BeanDisplay onActionFromLink4() {
// return a component as ajax result.
return beanDisplay;
}

// JSONArray onActionFromLink2() {
// return new JSONArray("[{user: 'test', firstName: 'yu'}]");
// }

// Component onActionFromLink4() {
// return componentSource.getPage("Start");
// }

public Date getStr() {
return new Date();
}

}
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd">
<head>
<title>ajax in tapestry5</title>
</head>
<body>
<div style="margin-left: 50px">
zone1:<t:zone t:id="zone1">ajax</t:zone>
<t:actionLink id="link1" t:id="link1">用ajax返回ResponseStream更新zone1,此链接通过ClientBehaviorSupport关联到zone1</t:actionLink>
<br />
zone2:<t:zone t:id="zone2">ajax</t:zone>
<t:actionLink t:id="link2" t:zone="zone2">update zone2 using json Object</t:actionLink>
<br />
zone3:<t:block t:id="block">${str}</t:block>
<t:zone t:id="zone3">
<t:delegate to="block"/>
</t:zone>
<a t:type="actionlink" t:id="link3" href="#" t:zone="zone3">update zone3 using Block</a>
<br />
<t:block><t:beanDisplay t:object="this"/></t:block>
zone4:<t:zone t:id="zone4">ajax</t:zone>
<t:actionLink t:id="link4" t:zone="zone4">update zone4 using Component</t:actionLink>
</div>
</body>
</html>

Sunday, October 26, 2008

RenderSupport Usage in Tapestry5

RenderSupport是在写组件中非常有用的一个service,主要用于提供对组件渲染的支持,可以用其导入css/javascript文件,最重要的一个功能是其可以为组件生成客户端HTML标签的唯一id。
要生成此客户端的id,可以用二个方法产生,一是RenderSupport.allocateClientId(String id),由自己指定一个id字符串,如果一个页面中包含多个相同组件,则第二个之后的组件会在此id后加上"_"和0开始的数字做为其id。
另外是用RenderSupport.allocateClientId(ComponentResources resources),resources会抽取其组件的id做为其客户端的id值。
举例写一个checkBoxes组件,需要提一点是不要分配"checkbox"做为组件的id,这个会导致server崩掉,Tapestry5的一个bug,还没有解决。

public class CheckBoxes {

@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
private String value;

@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
private String name;

@Parameter
private boolean checked;

@Inject
private Request request;

@Inject
private ComponentResources resources;

@Inject
private RenderSupport renderSupport;

@BeginRender
void begin(MarkupWriter writer) {
String id = renderSupport.allocateClientId("chk"); // don't use checkbox.
System.out.println(id);
Element checkbox = writer.element("input", "type", "checkbox", "name", name, "id", id, "value", value);
checkbox.attribute("checked", checked ? "checked" : null);
}

@AfterRender
void after(MarkupWriter writer) {
writer.end();
}

}

Explain onActivate/onPassivate of Tapestry5

用Tapestry5开发页面过程中,最常用到的二个页面方法(事件处理器)就是onActivate()和onPassivate()。
onActivate()方法是在此页面被激活后调用的,可以用此方法接收传给页面的参数(用官方的说法是以Array/List形式返回页面的activation context),此方法可以通过重载来接收数量不同的参数,并且其中参数少于等于URL InternalConstants.PAGE_CONTEXT_NAME传进来的参数数量的onActivate()方法都会被调用一次,其中无参的onActivate()方法肯定会被调用,并且是最后被调用,如后面例子所示。

注意,如果在Tapestry5中集成了tapestry-hibernate包,并且在passivate context中返回的是Hibernate实体的情况下,则可以在onActivate()中直接接收这些Hibernate实体对象,Tapestry会在passivate时自动从这些实体对象中提取id到页面URL ,并且在activate时自动转回Hibernate实体对象。Tapestry会在后台去查询数据库,如果页面很简单可以这么用,复杂页面不建议这么做。

onPassivate()方法是在页面渲染中,由LinkFactory生成每个actionLink或者返回自身页的pageLink时都会触发此事件,因此这个passivate事件在一个页面渲染中可能会重复调用多次。会将此方法返回的结果被encode后赋给InternalConstants.PAGE_CONTEXT_NAME,固化到所有返回自身页面的URL后面。对于actionLink和pageLink稍有不同的是,actionLink不管事件处理后重定向去哪,URL后都会跟上此参数,因其事件触发后先返回自身页面,而pageLink如果是指向别的页面,则不会触发此事件,URL后也不会带上此参数,如果需要传参给其他页面则通过pageLink的context参数指明参数值,如果pageLink是返回自身页面,则跟actionLink一样会在URL上直接跟上onPassivate返回的值,这样当前页面的一些变量状态就可以不用@Persist,而用onPassivate/onActivate进行传递。

关于onActivate/onPassivate更详细的内容可从以下接口和类中了解:ComponentResources/ComponentEventRequestHandler/ComponentEventRequestFilter/ComponentEventRequestHandler/ComponentEventRequestParameters/ComponentEventDispatcher/EventConstants/InternalConstants/LinkFactory/LinkFactoryImpl/PageLink/EventLink/ActionLink等。

其中ComponentEventRequestHandler可处理的事件请求形式有:

* /context/pagename:eventname -- event on the page, no action context
* /context/pagename:eventname/foo/bar -- event on the page with action context "foo", "bar"
* /context/pagename.foo.bar -- event on component foo.bar within the page, default event, no action context
* /context/pagename.foo.bar/baz.gnu -- event on component foo.bar within the page, default event, with action context "baz", "gnu"
* /context/pagename.bar.baz:eventname/foo/gnu -- event on component bar.baz within the page with action context "foo" , "gnu"


关于onActivate/onPassivate的一个测试例子:
java:
public class Test {

void onActivate() {
System.out.println("must be revoked when page be requested");
}

void onActivate(int id) {
System.out.println(id);
}

void onActivate(int id1, int id2) {
System.out.println(id1);
System.out.println(id2);
}

int onPassivate() {
System.out.println("passivate context");
return 1;
}

void onActionFromLink() {
}

void onRedirect() {
}
}
tml:
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd">
<a href="/Test">Test</a>
<br />
<t:actionLink t:id="link">ActionLink</t:actionLink>
<br />
<t:eventLink t:event="redirect" t:context="literal:1">EventLink1</t:eventLink>
<br />
<t:eventLink t:event="redirect">EventLink2</t:eventLink>
<br />
<t:pageLink t:page="Test">Self page Link</t:pageLink>
<br />
<t:pageLink t:page="Start">Another page Link</t:pageLink>
</html>
其中onPassivate()方法会被调用4次。
Reference:
http://tapestry.apache.org/tapestry5/apidocs/org/apache/tapestry5/internal/services/ComponentEventDispatcher.html

Saturday, October 25, 2008

Page LifeCycle Methods in Tapestry5

当组件或者页面中有方法用@PageLoaded这个Mathod Annotation声明过,则此方法只会在页面第一次完全加载时调用一次,以后页面直接从PagePool中获取的话,将不会再调用这个方法,但页面生命周期中的另外二个方法会继续被调用(pageAttached/pageDetached),页面生命周期方法必须为无参方法并且只能返回void值。

@PageLoaded
public void pageLoaded() {
System.out.println("page be loaded and run only once.");
}

Reference:http://tapestry.apache.org/tapestry5/apidocs/org/apache/tapestry5/annotations/PageLoaded
http://tapestry.apache.org/tapestry5/guide/lifecycle.html

Usage of MarkupWriter and Element in Tapestry5

可以在 @BeginRender 或者 @AfterRender 等 Annotation 声明过的方法内注入 MarkupWriter,用其以 XML 形式组织成一个 DOM 对象来渲染 Tapestry 组件,或者用其调整页面模板中的某个Element,修改其内容或者属性。可以通过 MarkupWriter 接口或者是 Element 类提供的方法操作这个 DOM 对象。
做一个Tapestry input组件的简单例子,无需模板文件:

public void afterRender(MarkupWriter writer) {
Element input = writer.element("input", "id", "input1", "name", "inputName", "value", "inputValue");
input.attribute("type", "text");
writer.end();
}
其中要注意如果用writer.element()打开一个元素标签时,要用writer.end()方法关闭此元素标签。
也可以在 Tapestry Page Class 中可以动态修改其模板文件,如下例子修改页面模板中一个div的文字内容和div属性。
page:
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.dom.Element;

public class Test {

public void afterRender(MarkupWriter writer) {
Element elem = writer.getDocument().getElementById("elemId");
elem.text(" This text added by Element.text method.");
elem.attribute("style", "border: #ddd 1px solid");
}
}
tml:
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd">
<div id="elemId">old inner text.</div>
</html>

在Tapestry5中,假如一个render方法名即符合Tapestry5的命名约定,又对方法做了Annotation声明,当二者不一致时,则此方法在二个render阶段都会被调用。
例如一个方法名叫afterRender,同时在方法中加了@BeginRender的修饰,则此方法在beginRender和afterRender这二个阶段都会被调用。
另外@Inject另外二个服务到页面中,也可以生成MarkupWriter对象,再用此对象操作模板。
@Inject
private ResponseRenderer responseRenderer;

@Inject
private MarkupWriterFactory factory;

如下方式在程序中也可得到MarkupWriter对象。
ContentType contentType = responseRenderer.findContentType(this);
MarkupWriter writer = factory.newMarkupWriter(contentType);

CSS border-color 说明

设置Block Element的边框属性是比较常见的,如:

.divBorder {
border: #ddd 5px solid;
}

但有时候Block Element需要设置一个宽度,却不需要设置颜色,可将border-color设置为transparent,如下所示:
.divBorder {
border: transparent 5px solid;
}

Sunday, October 12, 2008

Inject html string into a iframe

var text = "<div id='storeArea'>test</div>";
var content = "<html><body>" + text + "</body></html>";
var iframe = document.createElement("iframe");
document.body.appendChild(iframe);

var doc = iframe.document;
if(iframe.contentDocument)
doc = iframe.contentDocument; // For NS6
else if(iframe.contentWindow)
doc = iframe.contentWindow.document; // For IE5.5 and IE6

// Put the content in the iframe
doc.open();
doc.writeln(content);
doc.close();
// Load the content into a TiddlyWiki() object
var storeArea = doc.getElementById("storeArea");
console.log(storeArea);

Reference:
http://softwareas.com/injecting-html-into-an-iframe

Unicode spaces and RLO/LRO

<p>看下面2行的区别并复制下面第一行到任何文本编辑器中查看效果</p>
‮tset (e202u\:值edocinu)OLR符字制控
‭控制字符LRO(unicode值:\u202d) test
<p>其他Unicode空白字符</p>
<p>&#8234;&#8234;test</p>
<p>&#8235;&#8235;test</p>
<p>&#8236;&#8236;test</p>
<p>&#8237;&#8237;test</p>
<p>&#8238;&#8238;test</p>

另:这个如果用vim看的话,能看到这些unicode space characters,如\u202e这个在vim里会是<202e>这样的一个字符,可以被复制粘贴。
Reference:
http://www.cs.tut.fi/~jkorpela/chars/spaces.html

如何禁止网页打开时IE弹出的安全警告

当直接双击打开一个有javascript代码的网页,IE会在窗口顶部出现一条黄色警告信息,内容如下所示:
为了有利于保护安全性,IE已限制此网页运行可以访问计算机的脚本或 ActiveX 控件。请单击这里获取选项...
要取消此信息,只要在网页源码顶部的!DOCTYPE声明下面加一行代码,即可禁止此警告条出现:
<!-- saved from url=(0022) -->
这句话的作用是让Internet Explorer 使用 Internet 区域的安全设置,而不是本地计算机区域的设置。
Reference:
http://zhidao.baidu.com/question/33183687.html?fr=qrl&fr2=query&adt=0_88
http://zhidao.baidu.com/question/3693592.html?fr=qrl

Javascript demo scene [Cool]

用极少的javascript代码实现非常cool的效果,都用到了数学函数。

<pre id=B><script>setInterval("for(d='p01‡*×:,~. ',C=Math.cos(n-=88),S=Math.sin(n),Y=m=1+C,z=2048;z;Y-=m/16)for(d+='<br>',X=m;--z&63;X-=m/32,d+=d.charAt(k))for(r=i=k=0;++k+r*r+i*i<13;i=t)t=2*r*i-X*C+Y*S,r=r*r-i*i-X*S-Y*C+C-1;B.innerHTML=d",n=9)
</script>

<body id=B text=snow bgColor=0><script>Ô=setInterval("m='p01 256b Starfield';c=Math.cos;for(ô=0;ô<65;)m+='<p style=position:absolute;top:'+(50+(z=399/(73-(++ô+Ô++&63)))*c(ô*.9))+'%;left:'+(50+z*c(ô))+(z>>4?'%>·':'%;color:#456>.');B.innerHTML=m",9)</script>

<tt id=B style=line-height:1ex><script>setInterval("w='<br>';b=[,,,,,].join('P01 256b JS TUNNEX - ').substr(++t%21,65)+w;for(y=-n;n>++y;)for(b+=w,x=-n;n>++x;)b+=((399/Math.sqrt(x*x+y*y)+t)^(Math.atan2(y,x)*20.4+t))&8?'W':' ';B.innerHTML=b",t=n=33)</script>

Reference:
http://www.p01.org/releases/Demoscene/

MD5 值相同的二个字符串

d131dd02c5e6eec4693d9a0698aff95c 2fcab58712467eab4004583eb8fb7f89 
55ad340609f4b30283e488832571415a 085125e8f7cdc99fd91dbdf280373c5b
d8823e3156348f5bae6dacd436c919c6 dd53e2b487da03fd02396306d248cda0
e99f33420f577ee8ce54b67080a80d1e c69821bcb6a8839396f9652b6ff72a70
d131dd02c5e6eec4693d9a0698aff95c 2fcab50712467eab4004583eb8fb7f89 
55ad340609f4b30283e4888325f1415a 085125e8f7cdc99fd91dbd7280373c5b
d8823e3156348f5bae6dacd436c919c6 dd53e23487da03fd02396306d248cda0
e99f33420f577ee8ce54b67080280d1e c69821bcb6a8839396f965ab6ff72a70
这二个字符串的MD5值会冲突,值为:79054025255fb1a26e4bc422aef54eb4. 求值程序perl版及ruby版本如下:
#!/usr/bin/perl -w

use strict;

my $v1=<<END_V1;
d1 31 dd 02 c5 e6 ee c4 69 3d 9a 06 98 af f9 5c
2f ca b5 87 12 46 7e ab 40 04 58 3e b8 fb 7f 89
55 ad 34 06 09 f4 b3 02 83 e4 88 83 25 71 41 5a
08 51 25 e8 f7 cd c9 9f d9 1d bd f2 80 37 3c 5b
d8 82 3e 31 56 34 8f 5b ae 6d ac d4 36 c9 19 c6
dd 53 e2 b4 87 da 03 fd 02 39 63 06 d2 48 cd a0
e9 9f 33 42 0f 57 7e e8 ce 54 b6 70 80 a8 0d 1e
c6 98 21 bc b6 a8 83 93 96 f9 65 2b 6f f7 2a 70
END_V1

my $v2=<<END_V2;
d1 31 dd 02 c5 e6 ee c4 69 3d 9a 06 98 af f9 5c
2f ca b5 07 12 46 7e ab 40 04 58 3e b8 fb 7f 89
55 ad 34 06 09 f4 b3 02 83 e4 88 83 25 f1 41 5a
08 51 25 e8 f7 cd c9 9f d9 1d bd 72 80 37 3c 5b
d8 82 3e 31 56 34 8f 5b ae 6d ac d4 36 c9 19 c6
dd 53 e2 34 87 da 03 fd 02 39 63 06 d2 48 cd a0
e9 9f 33 42 0f 57 7e e8 ce 54 b6 70 80 28 0d 1e
c6 98 21 bc b6 a8 83 93 96 f9 65 ab 6f f7 2a 70
END_V2

my $p=join("",map {chr(hex($_))} split /\s+/, $v1);
my $q=join("",map {chr(hex($_))} split /\s+/, $v2);

# print $p, $q;
print `echo -n \'$p\'|md5`; # linux md5sum, mac md5
print `echo -n \'$q\'|md5`; # linux md5sum, mac md5

Ruby版:
#!/usr/bin/ruby -w
require 'digest/md5'

v1=<<END_V1;
d1 31 dd 02 c5 e6 ee c4 69 3d 9a 06 98 af f9 5c
2f ca b5 87 12 46 7e ab 40 04 58 3e b8 fb 7f 89
55 ad 34 06 09 f4 b3 02 83 e4 88 83 25 71 41 5a
08 51 25 e8 f7 cd c9 9f d9 1d bd f2 80 37 3c 5b
d8 82 3e 31 56 34 8f 5b ae 6d ac d4 36 c9 19 c6
dd 53 e2 b4 87 da 03 fd 02 39 63 06 d2 48 cd a0
e9 9f 33 42 0f 57 7e e8 ce 54 b6 70 80 a8 0d 1e
c6 98 21 bc b6 a8 83 93 96 f9 65 2b 6f f7 2a 70
END_V1

v2=<<END_V2;
d1 31 dd 02 c5 e6 ee c4 69 3d 9a 06 98 af f9 5c
2f ca b5 07 12 46 7e ab 40 04 58 3e b8 fb 7f 89
55 ad 34 06 09 f4 b3 02 83 e4 88 83 25 f1 41 5a
08 51 25 e8 f7 cd c9 9f d9 1d bd 72 80 37 3c 5b
d8 82 3e 31 56 34 8f 5b ae 6d ac d4 36 c9 19 c6
dd 53 e2 34 87 da 03 fd 02 39 63 06 d2 48 cd a0
e9 9f 33 42 0f 57 7e e8 ce 54 b6 70 80 28 0d 1e
c6 98 21 bc b6 a8 83 93 96 f9 65 ab 6f f7 2a 70
END_V2

nv1 = v1.split(/\s+/).collect{|char| char.hex.chr}.join("")
nv2 = v2.split(/\s+/).collect{|char| char.hex.chr}.join("")

puts Digest::MD5.hexdigest(nv1)
puts Digest::MD5.hexdigest(nv2)


Reference: http://www.mathstat.dal.ca/~selinger/md5collision/

Google favicon convert to png service

google在线转favicon为png的一个服务,只要将domain值换成所要的域名地址即可,如下:
http://www.google.com/s2/favicons?domain=google.com

Saturday, October 11, 2008

Apache SSL证书请求文件(CSR)生成指南

1. 生成私钥 Generate the private key
$> openssl genrsa -des3 -out www.mydomain.com.key 1024
此命令将生成1024位的RSA私钥,私钥文件名为: www.mydomain.com.key,生成过程中会提示设定私钥密码,设置并备份密码,在以后安装证书到apache服务器之后,重启apache服务器时,需要输入此密码验证通过后才能启动!
2. 生成CSR文件 Generate the CSR
$> openssl req -new -key www.mydomain.com.key -out www.mydomain.com.csr
此命令将提示输入X.509证书所要求的字段信息,包括国家(中国添CN)、省份、所在城市、单位名称、单位部门名称(可以不填直接回车)。注意: 除国家缩写必须填CN外,其余都可以是英文或中文。
输入要申请SSL证书的域名,如果为www.domain.com申请SSL证书就不能只输入domain.com,要输入完整的域名,包括二级域名,SSL证书是严格绑定域名的。

Reference: http://www.wosign.com/support/CSRgen/Apache_CSR.htm

utf-8和Unicode之间相互转换

UTF-8是Unicode的实现方式之一。
UTF-8最大的一个特点,就是它是一种变长的编码方式。它可以使用1~4个字节表示一个符号,根据不同的符号而变化字节长度。
UTF-8的编码规则很简单,只有二条:
1)对于单字节的符号,字节的第一位设为0,后面7位为这个符号的unicode码。因此对于英语字母,UTF-8编码和ASCII码是相同的。
2)对于n字节的符号(n>1),第一个字节的前n位都设为1,第n+1位设为0,后面字节的前两位一律设为10。剩下的没有提及的二进制位,全部为这个符号的unicode码。

下表总结了编码规则,字母x表示可用编码的位。

Unicode符号范围 | UTF-8编码方式
(十六进制) | (二进制)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

以汉字"严"为例,演示如何实现UTF-8编码。
已知"严"的unicode是4E25(100111000100101),根据上表,可以发现4E25处在第三行的范围内(0000 0800-0000 FFFF),因此"严"的UTF-8编码需要三个字节,即格式是"1110xxxx 10xxxxxx 10xxxxxx"。然后,从"严"的最后一个二进制位开始,依次从后向前填入格式中的x,多出的位补0。这样就得到了,"严"的UTF-8编码是 "11100100 10111000 10100101",转换成十六进制就是E4B8A5。
在firebug中测试中文"胡"字:
>>> encodeURI('胡')
"%E8%83%A1"
>>> '胡'.charCodeAt().toString(16)
"80e1"
>>> '胡'.charCodeAt().toString(2)
"1000000011100001"
>>> parseInt('111010001000001110100001', 2)
15238049
>>> parseInt('111010001000001110100001', 2).toString(16)
"e883a1"

其中将1000000011100001对应位置补上110或者10,生成Unicode二进制值111010001000001110100001,反过来从Unicode转到UTF-8只要移除对应位置上的110和10即可得到UTF-8的二进制值。
Reference:
http://yuweijun.blogspot.com/2008/06/unicode.html
http://yuweijun.blogspot.com/2008/08/unicode-and-html-entities-in-javascript.html
http://dreamstone.javaeye.com/blog/77939

HowTo set width/height/font/fontSize of vim window

" set the screen width and height, the same as set columns and lines
win 80 25
" columns width of the display
" set co=80
" lines number of lines in the display
" set lines=24
" For Mac OS X you can use something like this: >
set guifont=Monaco:h12

XML operation using javascript E4X from Rhino javascript shell

Firstly, download Rhino and install it. Here is a tutorial.
Then, run below command line:

$> java org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 1 2008 03 06
js> var user = <user id="1"><name type="firstname">Yu</name><name type="lastname">test</name><country>zh_CN</country></user>;
js> user
<user id="1">
<name type="firstname">Yu</name>
<name type="lastname">test</name>
<country>zh_CN</country>
</user>
js> typeof a
undefined
js> typeof user
xml
js> user.name
<name type="firstname">Yu</name>
<name type="lastname">test</name>
js> user.country
zh_CN
js> user.id

js> user.@id
1
js> user.@id = 100
100
js> user
<user id="100">
<name type="firstname">Yu</name>
<name type="lastname">test</name>
<country>zh_CN</country>
</user>
js> user.name[0]
Yu
js> user.name += <name type="nickname">_test</name>;
<name type="firstname">Yu</name>
<name type="lastname">test</name>
<name type="nickname">_test</name>
js> user
<user id="100">
<name type="firstname">Yu</name>
<name type="lastname">test</name>
<name type="nickname">_test</name>
<country>zh_CN</country>
</user>
js> user.name[1]
test
js> user.name[1].@type
lastname
js> for each(var n in user.name) print("The " + n.@type + " name is " + n);
The firstname name is Yu
The lastname name is test
The nickname name is _test
js> for each(var n in user..name) print("The " + n.@type + " name is " + n);
The firstname name is Yu
The lastname name is test
The nickname name is _test
js> quit();

The user..name selector just like the "//" operator in XPath.
$> cat echo.js
for (i in arguments) {
print(arguments[i])
}

$> java org.mozilla.javascript.tools.shell.Main echo.js test yu from google
test
yu
from
google

Reference:
http://developer.mozilla.org/en/Rhino_Shell

Javascript event handler for text cut/paste/copy

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>some javascript element event example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>

<body>
<h3>Element.onpaste</h3>
<textarea id="editor" rows="3" cols="80" onpaste="pasteIntercept(event);">
Try pasting text into this area!
</textarea>

<h3>Log</h3>
<textarea rows="5" cols="80" id="log" readonly="true"></textarea>

<h3>Element.oncontextmenu</h3>
<div oncontextmenu="return false;" style="border: #ddd 1px solid; width: 642px; color: #369;">
prevent element context menu<br>
阻止此元素上的右键菜单弹出
</div>

<h3>Element.oncut and Element.copy</h3>
<input type="text" size="80" name="preventpaste" value="text can't be cut or copy!" oncut="return false" oncopy="return false"/>

<script type="text/javascript">
function log(txt)
{
document.getElementById("log").appendChild(document.createTextNode(txt + "\n"));
}

function pasteIntercept(event)
{
log("Pasting!");
event.preventDefault(); // event.returnValue = false; // IE
return false;
}
</script>

</body>
</html>

以上的几个方法在IE/Safari/Firefox3里都有对应的实现,在firefox3中测试通过,firefox2和opera未测试,应该还没有支持这些事件处理器。
Reference:
http://developer.mozilla.org/en/DOM/element.onpaste

Test javascript e4x in firefox3

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test javascript e4x</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>

也可以将script的type直接写成"text/javascript"<br/>
<script type="text/javascript;e4x=1">

var person = <description>
<name>_test</name>
<sex>male</sex>
<age>30</age>
</description>;

document.write("The person' name is '" + person.name + "'");

</script>

</body>
</html>

Tuesday, October 07, 2008

Import blogspot article to wordpress

一、首先修改以下url中的yourusername为你的blogger用户名后,打开此url,保存源代码为rss.xml。
http://yourusername.blogspot.com/feeds/posts/default?alt=rss

二、然后在wordpress控制台中导入此文件。

网上说直接下载blogspot根目录下面的那个rss.xml文件就可以导入,试了没有成功。
http://yourusername.blogspot.com/rss.xml

Monday, October 06, 2008

Tapestry5 中事件处理完成之后可以返回的对象类型

  • Nothing: 此时方法一般是void的,当前页面会被刷新。
  • String: 要求此string指向一个PageName。
  • Class: 返回一个SomePage.class。
  • Page: 返回一个实例化的page,此page被当前页面注入。
  • Link: 返回一个实现Link接口的实例,此Link会被转化成对应的URL并重定向到此页面,Link对象一般通过页面中注入的ComponentResources中的方法生成,如ComponentResources.createPageLink、ComponentResources.createActionLink。
  • Stream: 返回一个StreamResponse对象,如提供用户pdf/excel格式的下载,更多用于ajax返回。
  • URL: 返回一个URL对象,可以重定向到一个外部链接上去。
返回除以上几种对象之外的对象都会出错。
Reference: http://tapestry.apache.org/tapestry5/tapestry-core/guide/pagenav.html

Sunday, October 05, 2008

Firebug command line api 和 console api 中比较常用到的几个方法

1. $(id) 与 prototype 用法类似,只能传字符串的Element Id。
2. $$(selector) 与 prototype 用法类似,传一个CSS Selector字符串,另专门还有一个$x("xPath")方法接受xpath方式查询DOM节点。
3. dir(object) 遍历object所有属性,在console中打印出来。
4. clear() 清空console。
5. debug(fn) 在对应的fn方法第一行加一个断点,当此方法调用时就会进入此方法第一行,可进行断点调试此方法。对应的有undebug(fn)取消断点。

6. console.log(object[, object, ...]),console是Firebug在Firefox中添加的一个全局变量名。其log()方法会将对象打印到firebug控制台中,支持类似printf()的功能。
7. 同console.log()类似的还有console.debug(),console.info(),console.warn(),console.error()方法。
8. console.assert(expression[, object, ...])断言功能,用来检查表达式是否正确执行。

Reference: http://getfirebug.com/commandline.html
http://getfirebug.com/console.html

Extending javascript Function prototype object

Function.prototype.twice = function() {
var fn = this;
return function() {
return fn.call(null, fn.apply(null, arguments));
};
};

Function.prototype.twice2 = function() {
var fn = this;
return function() {
console.log(this); // Window Object
return fn.call(this, fn.apply(this, arguments));
};
};

function plus1(x) { return x + 1; }
var plus2 = plus1.twice();
var plus3 = plus1.twice2();
console.log(plus2(10)); // 12
console.log(plus3(10)); // 12
Reference:http://osteele.com/talks/ajaxian-2008/samples/idioms-9.js.html

Friday, October 03, 2008

Diefference between "function func(){}" and "var func = function(){}" in javascript


console.log(f); // undefined
console.log(h()); // true

// This line of code defines an unnamed function and stores a reference to it
// in the variable f. It does not store a reference to the function into a variable
// named fact, but it does allow the body of the function to refer to itself using
// that name.
var f = function fact(x) { if (x <= 1) return 1; else return x * fact(x - 1); };
try {
console.log(f);
console.log(fact);
} catch (e) {
console.error(e.message)
}
console.log(f(1));
console.log(f(2));
console.log(f(3));
var g = function (x) {if (x <= 1) return 1; else return x * arguments.callee(x - 1);};
console.log(g(4));
function h() {return true}

其中需要说明一下"var func = function(){}" 与 "function func(){}"这二者的区别是后者用function语句定义的variable会先于此function运行前被初始化,因此h()函数调用可以写在其定义语句之前,而前者用var声明的variable则只能在此变量声明之后才可以被调用,与其他用var声明的变量完全一样。
另"var f = function fact(x) { if (x <= 1) return 1; else return x * fact(x - 1); };"这个写法要注意是在javascript1.5版本之后才被实现。

JavaScript函数调用时的作用域链和调用对象是如何形成的及与闭包的关系

1、javascript解析器启动时就会初始化建立一个全局对象global object,这个全局对象就拥有了一些预定义的全局变量和全局方法,如Infinity, parseInt, Math,所有程序中定义的全局变量都是这个全局对象的属性。在客户端javascript中,Window就是这个javascript的全局对象
2、当javascript调用一个function时,会生成一个对象,称之为call object(调用对象),function中的局部变量和function的参数都成为这个call object的属性,以免覆写同名的全局变量。
调用对象: ECMAScript规范术语称之为activation object(活动对象)。
3、javascript解析器每次执行function时,都会为此function创建一个execution context执行环境,在此function执行环境中最重要的一点就是function的作用域链scope chain,这是一个对象链,由全局对象调用对象构成,对象链具体构成过程见下面说明。
4、当javascript查询变量x的值时,就会检查此作用域链中第一个对象,可能是调用对象或者是全局对象,如果对象中有定义此x属性,则返回值,不然检查作用域链中的下一个对象是否定义x属性,在作用域链中没有找到,最后返回undefined。
5、当javascript调用一个function时,它会先将此function定义时的作用域作为其作用域链,然后创建一个调用对象,置于作用域链的顶部,function的参数及内部var声明的所有局部变量都会成为此调用对象的属性。
6、this关键词指向方法的调用者,而不是以调用对象的属性存在,同一个方法中的this在不同的function调用中,可能指向不同的对象。
7、The Call Object as a Namespace
(function() {
// 在方法体内用var声明的所有局部变量,都是以方法调用时创建的调用对象的属性形式存在。
// 这样就避免与全局变量发生命名冲突。
})();
8、javascript中所有的function都是一个闭包,但只有当一个嵌套函数被导出到它所定义的作用域外时,这种闭包才强大。如果理解了闭包,就会理解function调用时的作用域链和调用对象,才能真正掌握javascript。
9、当一个嵌套函数的引用被保存到一个全局变量或者另外一个对象的属性时,在这种情况下,此嵌套函数有一个外部引用,并且在其外围调用函数的调用对象中有一个属性指向此嵌套函数。因为有其他对象引用此嵌套函数,所以在外围函数被调用一次后,其创建的调用对象会继续存在,并不会被垃圾回收器回收,其函数参数和局部变量都会在这个调用对象中得以维持,javascript代码任何形式都不能直接访问此对象,但是此调用对象是嵌套函数被调用时创建的作用域链中的一部分,可以被嵌套函数访问并修改。

Thursday, October 02, 2008

jQuery event model test


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
div, p {
margin: 2px;
border: #eee 1px solid;
min-height: 20px;
}
table, td {
width: 100%;
border: #ddd 1px solid;
}
.block {
position: relative;
width: 200px;
background-color: #828;
}
.data {
background-color: #333;
}
</style>
</head>
<body>
<p>Click or double click here.</p>
<span></span>
<div class="data">click here and see console log</div>
<p id="myCustom">Has an attached custom event.</p>
<button id="customButton">Trigger custom event</button>
<span style="display:none;" id="eventSpan"></span>

<div>
<p>
Binds a handler to a particular event (like click) for each matched element. Can also bind custom events.<br>
The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler has to return false. Note that this will prevent handlers on parent elements from running but not other jQuery handlers on the same element.
</p>
<p>
In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second parameter (and the handler function as the third), see second example.
</p>
<button id="go">Go</button>
<button id="stop">STOP!</button>
<button id="back">Back</button>
<div class="block">div.block has animation</div>
</div>

<div class="oneClick"></div>
<div class="oneClick"></div>
<div class="oneClick"></div>
<div class="oneClick"></div>
<div class="oneClick"></div>
<div class="oneClick"></div>
<div class="oneClick"></div>
<div class="oneClick"></div>
<p id="p4click">Click a green square...</p>

<button id="button1">Button #1</button>
<button id="button2">Button #2</button>
<div><span id="spanFirst">0</span> button #1 clicks.</div>
<div><span id="spanLast">0</span> button #2 clicks.</div>

<button id="old">.trigger("focus")</button>
<button id="new">.triggerHandler("focus")</button><br/><br/>
<input type="text" value="To Be Focused" class="handler"/>

<script type="text/javascript" charset="utf-8">
$("p").bind("click", function(e){
console.log(e);
var str = "( " + e.pageX + ", " + e.pageY + " )";
$("span").text("Click happened! " + str);
});
$("p").bind("dblclick", function(){
$("span").text("Double-click happened in " + this.tagName);
});

function handler(event) {
console.log(event.data.foo);
}

// You can pass some extra data before the event handler:
$("div.data").bind("click", {foo: "bar"}, handler)

// To cancel a default action and prevent it from bubbling up, return false:
$("form").bind("submit", function() {return false; })

// Can bind custom events too.
$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("#eventSpan").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("#customButton").click(function () {
$("#myCustom").trigger("myCustomEvent", [ "John" ]);
});

// Start animation
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});

// Stops all the currently running animations on all the specified elements.
// If any animations are queued to run, then they will begin immediately.
// Stop animation when button is clicked
$("#stop").click(function(){
$(".block").stop();
});

// Start animation in the opposite direction
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});

var n = 0;
$("div.oneClick").one("click", function(){
var index = $("div.oneClick").index(this);
$(this).css({ borderStyle:"inset",
cursor:"auto" }).text("this div be clicked");
$("#p4click").text("Div at index #" + index + " clicked." +
" That's " + ++n + " total clicks.");
});

$("#button1").click(function () {
update($("#spanFirst"));
});
$("#button2").click(function () {
$("#button1").trigger('click');
update($("#spanLast"));
});

function update(j) {
var n = parseInt(j.text(), 0);
j.text(n + 1);
}

// To pass arbitrary data to an event:
// $("p").click( function (event, a, b) {
// when a normal click fires, a and b are undefined
// for a trigger like below a refers too "foo" and b refers to "bar"
// } ).trigger("click", ["foo", "bar"]);
$("#p4click").bind("myEvent", function (event, message1, message2) {
console.log(message1 + ' ' + message2 + " from element: " + this.id);
});
$("#p4click").trigger("myEvent", ["Hello","World!"]);

// This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
$("#old").click(function(){
$("input.handler").trigger("focus");
});
$("#new").click(function(){
$("input.handler").triggerHandler("focus");
});
$("input.handler").focus(function(){
console.log(arguments[0]); // Pass along a fake event by jQuery and no need to fix fake event
$("<span>Focused!</span>").appendTo("body").fadeOut(3000);
});
</script>
</body>
</html>

parseInt() of javascript

parseInt(string, radix),其中parseInt(string, 0)与parseInt(string, 10)结果是相同的。


>>> parseInt('22', 0)
22
>>> parseInt('22', 10)
22
>>> parseInt('22', 8)
18

Wednesday, October 01, 2008

jQuery child selector usage example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
.green {
color: green;
}
.last {
background-color: #ddd;
}
div {
margin: 2px;
border: #eee 1px solid;
}
table, td {
width: 100%;
border: #ddd 1px solid;
}
</style>
</head>
<body>
<div>
<span>John,</span>
<span>Karl,</span>
<span>Brandon</span>
</div>
<div>
<span>Glen,</span>
<span>Tane,</span>
<span>Ralph</span>
</div>
<div>
<button>Sibling!</button>
<button>Sibling!</button>
</div>

<div>
<button>Sibling!</button>
</div>
<div>
None
</div>

<div>
<button>Sibling!</button>
<button>Sibling!</button>
<button>Sibling!</button>
</div>

<div>
<button>Sibling!</button>
</div>

<div>
<ul>
<li>John</li>
<li>Karl</li>
<li>Brandon</li>
</ul>
</div>

<div>
<ul>
<li>Sam</li>
</ul>
</div>

<div>
<ul>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
<li>David</li>
</ul>
</div>

<div class="buttons">
<button>:nth-child(even)</button>
<button>:nth-child(odd)</button>
<button>:nth-child(3n)</button>
<button>:nth-child(2)</button>
</div>
<div class="buttons">
<button>:nth-child(3n+1)</button>
<button>:nth-child(3n+2)</button>
<button>:even</button>
<button>:odd</button>
</div>
<div>
<table>
<tr><td>John</td></tr>
<tr><td>Karl</td></tr>
<tr><td>Brandon</td></tr>
<tr><td>Benjamin</td></tr>
</table>
</div>
<div>
<table>
<tr><td>Sam</td></tr>
</table>
</div>
<div>
<table>
<tr><td>Glen</td></tr>
<tr><td>Tane</td></tr>
<tr><td>Ralph</td></tr>
<tr><td>David</td></tr>
<tr><td>Mike</td></tr>
<tr><td>Dan</td></tr>
</table>
</div>
<span>
tr<span id="inner"></span>
</span>

<script type="text/javascript" charset="utf-8">
// Matches the first child of its parent.
$("div span:first-child")
.css("text-decoration", "underline")
.hover(function () {
$(this).addClass("green");
}, function () {
$(this).removeClass("green");
});

$("div span:last-child")
.css({color: "red", fontSize: "80%"})
.hover(function () {
$(this).addClass("last");
}, function () {
$(this).removeClass("last");
});

$("div button:only-child").text("Alone Button in Div");
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");

$("div.buttons button").click(function () {
console.log(this);
var str = $(this).text();
$("tr").css("background", "white");
$("tr" + str).css("background", "#f98");
$("#inner").text(str);
});
</script>
</body>
</html>

jQuery attributes selectors usage example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
</head>
<body>
<input name="milkman" />
<input name="letterman2" />
<input name="newmilk" />
<input name="newsletter" />
<input name="jobletter" />
<input name="jobletter2" />
<input id="man-news" name="man-news" />
<input id="letterman" name="new-letterman" />
<div>
<input type="radio" name="newsletter" value="Hot Fuzz" />
<span>name?</span>
</div>
<div>
<input type="radio" name="newsletter" value="Cold Fusion" />
<span>name?</span>
</div>
<div>
<input type="radio" name="accept" value="Evil Plans" />
<span>name?</span>
</div>
<div>no id</div>
<div id="hey">with id</div>
<div id="there">has an id</div>
<div>no id</div>

<script type="text/javascript" charset="utf-8">
// $("input[@name*='man']").val("has man in it!"); // the same below using XPath
$("input[name*='man']").val("has man in it!"); // attributeContains( String attribute, String value )
$("input[name^='news']").val("news here!");
$("input[name$='letter']").val("a letter"); // attributeEndsWith( String attribute, String value )
$("input[name='newsletter']").next().text(" is newsletter");
$("input[name!='newsletter']").next().text(" is not newsletter");

// one() function, The handler is executed only once for each element
$("div[id]").one("click", function(){
var idString = $(this).text() + " = " + $(this).attr("id");
$(this).text(idString);
});

$("input[id][name$='man']").val("only this one"); // Matches elements that have the specified attribute and it contains a certain value.
</script>
</body>
</html>

jQuery Contents and Visibility Selectors examples


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
div {
border: #ddd 1px solid;
min-height: 20px;
margin: 3px;
}
table, td {
border: #ddd 1px solid;
}
.first {
font-weight: bold;
}
.hider {}
.starthidden {}
</style>
</head>
<body>
<div>John Resig</div>

<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>

<p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>
<table>
<tr><td>TD #0</td><td></td></tr>
<tr><td>TD #2</td><td></td></tr>
<tr><td></td><td>TD#5</td></tr>
</table>

<div><p>Hello in a paragraph</p></div>
<div>Hello again! (with no paragraph)</div>

<span></span>
<div></div>
<div style="display:none;" class="hider">Hider!</div>
<div></div>

<div class="starthidden">Hider!</div>
<div></div>
<form>
<input type="hidden" />
<input type="hidden" />
<input type="hidden" />
</form>
<span> </span>
<button>Show hidden to see they don't change</button>
<div></div>
<div class="starthidden"></div>
<div></div>

<div></div>
<div style="display:none;"></div>

<script type="text/javascript" charset="utf-8">
$("div:contains('John')").css("text-decoration", "underline");
$("p").contents().not("[nodeType=1]").wrap("<b/>");
$("td:empty").text("Was empty!").css('background', 'rgb(255,220,200)');
$("div:has(p)").addClass("first");
$("td:parent").fadeTo(1500, 0.5);

// in some browsers :hidden includes head, title, script, etc... so limit to body
$("span:first").text("Found " + $(":hidden", document.body).length + " hidden elements total.");
$("div:hidden").filter('.hider').show(1000);
$("span:last").text("Found " + $("input:hidden").length + " hidden inputs.");

$("div:visible").click(function () {
$(this).css("background", "yellow");
});
$("button").click(function () {
$("div:hidden").show("fast");
});
</script>
</body>
</html>

jQuery Basic Selectors usage example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
table td {
border: #ddd 1px solid;
}
div {
min-height: 20px;
border: #ddd 1px solid;
margin: 3px;
}
.colored {
background-color: #919;
}
</style>
</head>
<body>
<div id="myID.entry[0]">id="myID.entry[0]"</div>
<div id="myID.entry[1]">id="myID.entry[1]"</div>
<div id="myID.entry[2]">id="myID.entry[2]"</div>
<span>span</span>
<p>p</p>
<p>p</p>
<div>div</div>
<span>span</span>

<p>p</p>
<div>div</div>
<b></b>

<table>
<tr><td>Row with Index #0</td></tr>
<tr><td>Row with Index #1</td></tr>
<tr><td>Row with Index #2</td></tr>
<tr><td>Row with Index #3</td></tr>
<tr><td>Row with Index #4</td></tr>
<tr><td>Row with Index #5</td></tr>
<tr><td>Row with Index #6</td></tr>
<tr><td>Row with Index #7</td></tr>
<tr><td>Row with Index #8</td></tr>
<tr><td>Row with Index #9</td></tr>
</table>
<h1>Header 1</h1>
<p>Contents 1</p>
<h2>Header 2</h2>
<p>Contents 2</p>

<div>
<input type="checkbox" name="a" />
<span>Mary</span>
</div>

<div>
<input type="checkbox" name="b" />
<span>Paul</span>

</div>
<div>
<input type="checkbox" name="c"/>

<span>Peter</span>
</div>

<button id="run">Run</button>
<div></div>
<div id="mover"></div>
<div></div>

<script type="text/javascript" charset="utf-8">
// isSimple = /^.[^:#\[\.]*$/; // if id concludes such as ( :, #, [, ] ), you should backslashed these chararcters.
console.log($("#myID\\.entry\\[0\\]"));
$("#myID\\.entry\\[1\\]").css("border","3px solid red");


var list = $("div,p,span").map(function () {
return this.tagName;
}).get().join(", ");
$("b").append(document.createTextNode(list));

// function animateIt() {
// // console.log('endless loop');
// $("#mover").slideToggle("slow", animateIt);
// }
// animateIt();
//
// $("#run").click(function(){
// $("div:animated").toggleClass("colored");
// });

$("tr:even").css("background-color", "#bbf");
$("tr:odd").css("background-color", "#ffb");

// Matches all elements that are headers, like h1, h2, h3 and so on.
$(":header").css({ background:'#ccc', color:'blue' });

$("input:last")[0].checked = true;
$("input:not(:checked) + span").css("background-color", "yellow");
$("input").attr("disabled", "disabled");

$("td:lt(4)").css("color", "red");
$("td:gt(4)").css("color", "green");

</script>
</body>
</html>

jQuery extend and Interoperability example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/prototype.js"></script>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
</head>
<body>
<div id="content" style="display:none">
div#content style="display:none"
<span>div > span</span>
<p>div > p</p>
</div>
<input type="checkbox" name="c1[]" value="1" id="c1">checkbox#c1
<input type="checkbox" name="c1[]" value="1" id="c2">checkbox#c2
<input type="checkbox" name="c1[]" value="1" id="c3">checkbox#c3

<input type="radio" name="r1" value="1" id="r1">raido#r1
<input type="radio" name="r1" value="1" id="r2" checked>raido#r2
<input type="radio" name="r3" value="1" id="r3">raido#r3
<input type="radio" name="r3" value="1" id="r4" checked>raido#r4

<script type="text/javascript" charset="utf-8">
// Extends the jQuery Object itself.
// jQuery.extend( Object object ) returns jQuery
jQuery.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});

// Result:
var min = jQuery.min(2,3); // => 2
var max = jQuery.max(4,5); // => 5
console.log(min);
console.log(max);

// jQuery.extend( Object target, Object object1, Object objectN ) returns Object
// Extend one object with one or more others, returning the original, modified, object.
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);

// Result:
settings == { validate: true, limit: 5, name: "bar" }
console.log(settings);

// jQuery.fn.extend( Object object ) returns jQuery
// Extends the jQuery element set to provide new methods (used to make a typical jQuery plugin).
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});

// Result:
jQuery("input[@type=checkbox]").check();
jQuery("input[@type=radio]").not("#r1").uncheck();

// Maps the original object that was referenced by $ back to $.
jQuery.noConflict();
// Do something with jQuery
jQuery("div > p").hide();
// Do something with another library's $()
$("content").style.display = 'block';

// Completely move jQuery to a new namespace in another object.
var dom = {};
dom.query = jQuery.noConflict(true);
// Do something with the new jQuery
dom.query("div > span").hide();
</script>
</body>
</html>

jQuery Object Accessors example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
p {
margin: 3px;
}
.first {
color: #f90;
}
.second {
color: #f00;
min-height: 20px;
border: #949 1px solid;
margin: 5px 0px;
}
.three {
font-size: 18px;
color: blue;
border: blue 1px solid;
cursor: pointer;
}
</style>
</head>
<body>
<div id="d1">div#d1</div>
<div class="first">div.first</div>
<div class="first">div.first</div>
<div class="first">div.first</div>
<p>one</p> <div><p>two</p></div> <p>three</p>
Reversed - <div id="reversed"></div>
To do list: <span class="three">click here to change</span>
<span></span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Play</li>
<li>Be merry</li>
</ul>
<button>Change colors</button>
<span>this span innerText will be changed.</span>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second" id="stop">colors change will stop here</div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>

<input type="checkbox" name="t1" value="test1" id="t1"/>checkbox#t1

<script type="text/javascript" charset="utf-8">
$("span.three").click(function () {
// console.log(arguments);
$("li").each(function(){
$(this).toggleClass("first");
});
});
$("button").click(function () {
$("div.second").each(function (index, domEle) {
// this == domEle, $(this) == jQuery Object
$(domEle).css("backgroundColor", "yellow");
if ($(this).is("#stop")) {
$("span").not(".three").text("Stopped at div index #" + index);
return false; // break loop
}
});
});
$("#reversed").html($("p").get().reverse().map(function(elem){
return elem.innerHTML;
}).join(','));
$("p").eq(2).text("four");
$("span, ul, li", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
$("span:first").text("Clicked on - " + domEl.tagName);
});
$("div").click(function () {
// this is the dom element clicked
var index = $("div").index(this);
$("span:last").text("That was div index #" + index);
});
$(document.body).click(function () {
// because span/ul/li has stopPropagation event, div will not be added.
$(document.body).append($("<div>"));
var n = $("div").length;
$("span:eq(1)").text("There are " + n + " divs." +
"Click to add more.");
}).trigger('click'); // trigger the click to start
</script>
</body>
</html>

jQuery core function examples


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="/lib/jquery/jquery-1.2.6.js"></script>
<style type="text/css" media="screen">
.first {
color: #f90;
}
.second {
color: #f00;
min-height: 20px;
border: #949 1px solid;
margin: 5px 0px;
}
.three {
float:right;
}
</style>
</head>
<body>
<div>Click here</div>
<div>to iterate through</div>
<div>these divs.</div>

<div id="d1">div#d1</div>
<div class="first">div.first</div>
<div class="first">div.first</div>
<div class="first">div.first</div>
<p>one</p> <div><p>two</p></div> <p>three</p>
To do list: <span class="three">(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>

<li>Be merry</li>
</ul>
<button>Change colors</button>
<span>this span innerText will be changed.</span>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second" id="stop">Stop here</div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>
<div class="second"></div>

<input type="checkbox" name="t1" value="test1" id="t1"/>

<script type="text/javascript" charset="utf-8">
$("<div><p>Hello</p></div>").appendTo("body");
// Does NOT work in IE:
// $("<input/>").attr("type", "checkbox").appendTo("body");
// Does work in IE:
$("<input type='checkbox'/>").appendTo("div.first");
$("<input type='checkbox'/>").insertBefore("#d1");
$(".first").hide();
$(function () {
console.log("document ready");
});
$("div > p").css("border", "1px solid gray");
$('input:checkbox').get(0).checked = true;
$(document.body).click(function () {
$("div").each(function (i) {
console.log(i);
if (i == 2) return true; // skip this step
if (i == 5) return false; // break loop
if (this.style.color != "blue") {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
$("span.three").click(function () {
$("li").each(function(){
$(this).toggleClass("first");
});
});
$("button").click(function () {
$("div.second").each(function (index, domEle) {
// this == domEle, $(this) == jQuery Object
$(domEle).css("backgroundColor", "yellow");
if ($(this).is("#stop")) {
$("span").not(".three").text("Stopped at div index #" + index);
return false; // break loop
}
});
});
</script>
</body>
</html>