Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Saturday, July 02, 2011

globalEval function of jQuery changed in version 1.6

globalEval function of jquery before version 1.6, such as 1.5.2 and 1.2.6, source code:

// Evalulates a script in a global context
globalEval: function( data ) {
if ( data && rnotwhite.test(data) ) {
// Inspired by code by Andrea Giammarchi
// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement,
script = document.createElement( "script" );

if ( jQuery.support.scriptEval() ) {
script.appendChild( document.createTextNode( data ) );
} else {
script.text = data;
}

// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
},

globalEval function of jquery 1.6 source code:
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},

Thursday, January 13, 2011

springmvc 中ajax提交发生乱码问题

这个问题目前只是在springmvc项目中碰到,在IE和Chrome中,当用jQuery.post()方法发起ajax请求时,Controller中收到的中文内容变成乱码了,而在firefox中用jQuery.post()进行ajax请求时是正常的。
在Controller中调用如下代码(项目为UTF-8编码):


// name 是post收到的字符串变量名
System.out.println(new String(name.getBytes(HTTP.ISO_8859_1), HTTP.UTF_8));

可以看到乱码恢复正常,说明IE和Chrome提交的ajax请求中的内容被编码成 ISO-8859-1 编码了。
而实际上,对于IE而已,所有的ajax请求都是以UTF-8方式发起的,通过以下方式设置ajax请求的编码为GBK实际是没有用的,服务器收到仍然是UTF-8编码的请求体:

xmlhttp.setRequestHeader( "Content-Type", "text/html;charset=GBK" );
// or
xmlhttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=GBK");

因此可以肯定是springmvc在收到POST请求后,将请求体的数据用 ISO-8859-1 编码来处理了,最后传到Controller中时变成了乱码,但是为何firefox中提交的却仍然是正确的呢?
在firebug中观察firefox中的ajax请求头,可以看到firebug中的提示:

Content-Type application/x-www-form-urlencoded; charset=UTF-8

而在IE中用http analysis工具看到的却是:

Content-Type application/x-www-form-urlencoded

google Chrome中与IE一样,ajax请求头中没有指明编码,所以Chrome和IE一样将发生乱码了。
查看jquery-1.4.4.js源码可以看到,jQuery中原来的 contentType设置为"application/x-www-form-urlencoded",IE和Chrome中的请求头显示是正确的,没有问题,反而是firefox将contentType中设置了编码。
从这个请求头分析来看,应该是springmvc没有得到请求的编码,而将其内容设置为ISO-8859-1了,因此发生了乱码的情况。

解决方法还是参考firefox的请求头,在contentType中指定编码,明确告诉服务器端,当前请求体的编码方式为UTF-8。

xmlhttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

如果使用jQuery发起ajax请求,javascript的代码改为如下方式发起ajax请求,而不是以$.post()和$.get()等快捷方法:

$.ajax({
url: url,
type: "POST",
dataType: "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: data,
complete:function(data) {
}
});

Thursday, August 20, 2009

Element Data in jQuery

Added in jQuery 1.2
Attaching data to elements can be hazardous.
Store data: jQuery.data(elem, "name", "value");
Read data: jQuery.data(elem, "name");
All data is stored in a central cache and completely garbage collected,
as necessary.

Added in jQuery 1.2.3
Can handle namespacing:


$("div").data("test", "original");
$("div").data("test.plugin", "new data");
$("div").data("test") == "original"; // true
$("div").data("test.plugin") == "new data"; // true

Advanced data handling can be overridden by plugins:

$(element).bind("setData.draggable", function(event, key, value) {
self.options[key] = value;
}).bind("getData.draggable", function(event, key) {
return self.options[key];
});

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>

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>

Wednesday, August 13, 2008

Tweak your Object constructor [javascript tips]

注意代码中的变量名和function名的关系,书写一定要分清楚各个变量的词法作用域:
第一种情况,虽然名字相同,但词法作用域不同,不相关系。

function Tweak() { // 这里的Tweak是window的一个全局方法
var Tweak = function() { // 这里的Tweak是一个局部变量名,与window.Tweak不相关
this.init(arguments[0]);
};
Tweak.prototype = { // 局部变量名
args: arguments,
init: function() {
console.log(arguments[0]); //firefox [1, 2] //safari: [object Arguments]
return this;
}
}
return new Tweak(arguments);
}

var t = Tweak(1,2);
console.log(t.args); // [1, 2] // [object Arguments]

第二种是变量名覆写了方法名
// 如果javascript代码如下
var Tweak = Tweak(1, 2); // javascript中的function会先被解析器解析,这里Tweak(1, 2)已经在调用下面的Tweak方法,但此方法调用完成后马上被变量Tweak覆写
function Tweak() {
var Tweak = function() { // 这里的Tweak是一个局部变量名,与window.Tweak不相关
this.init(arguments[0]);
};
Tweak.prototype = { // 局部变量名
args: arguments,
init: function() {
console.log(arguments[0]); //firefox [1, 2] //safari: [object Arguments]
return this;
}
}
return new Tweak(arguments);
}
// Tweak(1, 2); // 这句代码已经执行错误,因为Tweak已经是一个对象,而不是方法了。

第三种是方法名覆写了变量名
// 如果javascript代码如下
var Tweak = {};
Tweak = function () { // Tweak 变量被重新赋为一个function对象
var Tweak = function() { // 这里的Tweak是一个局部变量名,与window.Tweak不相关
this.init(arguments[0]);
};
Tweak.prototype = { // 局部变量名
args: arguments,
init: function() {
console.log(arguments[0]); //firefox [1, 2] //safari: [object Arguments]
return this;
}
}
return new Tweak(arguments);
}
Tweak(1, 2); // 这句代码可以执行

Saturday, March 15, 2008

Get parameter using php and compress queryString using javascript

在php中如果从一个form提交一个数组给php页面的时候,一般在form中就将对应的变量写为: name="arr[]", 这样就可以在接收页面直接用php取到$arr = $_POST["arr"];取到这个数组,如果用get方法传送的query String是这样子的话: ?arr=1&arr=2&arr=3 时, php则在用$_GET["arr"]获得arr时则会只得到最后赋值的3,这是php处理query String的方法。
对于SERVER一端还是会正常收到这个请求的query String: ?arr=1&arr=2&arr=3,仍可以用server端的脚本语言重新对参数进行分析,也可以用javascript在client端分析query String。
javascript compress query string:


function compress(data){
var q = {}, ret = "";
data.replace(/([^=&]+)=([^&]*)/g, function(m, key, value){
q[key] = (q[key] ? q[key] + "," : "") + value;
});
for ( var key in q )
ret = (ret ? ret + "&" : "") + key + "=" + q[key];
return ret;
}

or:

function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}

Reference:
Jone Resig's Blog