jQuery的Validation插件
最新最全的jQuery插件可以從jQuery的官方網(wǎng)站上面獲得,jQuery下載驗(yàn)證插件的地址是http://plugins.jquery.com/在打開頁(yè)面的左上角’Search’框中輸入validation就可以找到我們想要的驗(yàn)證插件了,在http://plugins.jquery.com/project/validate下,我們找到了目前最新的版本(2009年6月17日)官方推出的1.5.5版的validate.js.
Validation插件式歷史悠久的jQuery插件之一,經(jīng)過(guò)了全球各種項(xiàng)目的驗(yàn)證,得到了很多WEB開發(fā)者的好評(píng),作為一個(gè)表單驗(yàn)證的解決方案,Validation有很多的優(yōu)點(diǎn),比如:內(nèi)置的驗(yàn)證規(guī)則,可以自定義驗(yàn)證規(guī)則,簡(jiǎn)單而且強(qiáng)大的驗(yàn)證信息提示,實(shí)時(shí)進(jìn)行驗(yàn)證的功能.都可以令前臺(tái)開發(fā)變得非常的簡(jiǎn)單.Validation具有內(nèi)置的必填,數(shù)字,Email,URL等多種驗(yàn)證規(guī)則.實(shí)時(shí)驗(yàn)證方面,通過(guò)blur和keyup時(shí)間來(lái)觸發(fā)驗(yàn)證規(guī)則,可以達(dá)到實(shí)時(shí)驗(yàn)證的目的.
下面是一個(gè)簡(jiǎn)單的例子,HTML和jQuery代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery之驗(yàn)證插件</title>
<script type='text/javascript' src='jquery-1.3.2.js'></script>
<!-- 引入了jQuery庫(kù)之后,繼續(xù)引入validation插件 -->
<script type='text/javascript' src='jquery.validate.js'></script>
<style type='text/css'>
*{font-family:Verdana;font-size:96%;}
label.error{float:none;color:red;padding-left:.5em;vertical-align:top;}
p{clear:both;}
.submit{margin-left:12em;}
em{font-weight:bold;vertical-align:top;}
</style>
<script type='text/javascript'>
$(document).ready(function(){
//確定哪一個(gè)表單需要進(jìn)行驗(yàn)證
$('#commentForm').validate();
});
</script>
</head>
<body>
<form class='cmxform' id='commentForm' method='get' action='#'>
<fieldset>
<legend>一個(gè)簡(jiǎn)單的帶有提示的評(píng)論例子</legend>
<p>
<label for='cusername'>姓名</label><em>*</em>
<!-- 針對(duì)不同的字段,進(jìn)行驗(yàn)證規(guī)則編碼,設(shè)置字段相應(yīng)的屬性 -->
<!-- class='required'來(lái)設(shè)置必填驗(yàn)證,minlength='2'設(shè)置最小長(zhǎng)度驗(yàn)證 -->
<input id='cusername' name='username' size='25' class='required' minlength='2'/>
</p>
<p>
<label for='cemail'>電子郵件</label><em>*</em>
<!-- class='required,email'為必填內(nèi)容和email規(guī)則驗(yàn)證 -->
<input id='cemail' name='email' size='25' class='required email'/>
</p>
<p>
<label for='curl'>網(wǎng)址</label><em>*</em>
<!-- class='url'設(shè)置url驗(yàn)證 -->
<input id='curl' name='url' size='25' class='url' value=''/>
</p>
<p>
<label for='ccomment'>你的評(píng)論</label><em>*</em>
<!-- 對(duì)評(píng)論textarea進(jìn)行必填驗(yàn)證 -->
<textarea id='ccomment' name='comment' cols='25' class='required'></textarea>
</p>
<p>
<input class='submit' type='submit' value='提交'>
</p>
</fieldset>
</form>
</body>
</html>
上面的代碼實(shí)現(xiàn)了如下的驗(yàn)證:
1) 對(duì)”姓名”的必填和長(zhǎng)度至少為2為的驗(yàn)證
2) 對(duì)”電子郵件”的驗(yàn)證和是否為E-mail格式的驗(yàn)證
3) 對(duì)”網(wǎng)址”是否為url的驗(yàn)證
4) 對(duì)”你的評(píng)論”的必填驗(yàn)證
5) 提供了在用戶輸入的時(shí)候?qū)﹂L(zhǎng)度的實(shí)時(shí)驗(yàn)證
只需要完成如下幾步,就可以將一個(gè)普通的表單變成一個(gè)可以進(jìn)行驗(yàn)證的表單:
1) 引入jQuery庫(kù)和Validation插件
view plaincopy to clipboardprint?
<mce:script type='text/javascript' src="jquery-1.3.2.js" mce_src="jquery-1.3.2.js"></mce:script>
<!-- 引入了jQuery庫(kù)之后,繼續(xù)引入validation插件 -->
<mce:script type='text/javascript' src="jquery.validate.js" mce_src="jquery.validate.js"></mce:script>
<mce:script type='text/javascript' src="jquery-1.3.2.js" mce_src="jquery-1.3.2.js"></mce:script>
<!-- 引入了jQuery庫(kù)之后,繼續(xù)引入validation插件 -->
<mce:script type='text/javascript' src="jquery.validate.js" mce_src="jquery.validate.js"></mce:script>
2) 確定是哪一個(gè)表單需要被驗(yàn)
view plaincopy to clipboardprint?
$(document).ready(function(){
//確定哪一個(gè)表單需要進(jìn)行驗(yàn)證
$('#commentForm').validate();
});
$(document).ready(function(){
//確定哪一個(gè)表單需要進(jìn)行驗(yàn)證
$('#commentForm').validate();
});
3) 針對(duì)不同的字段,進(jìn)行驗(yàn)證規(guī)則的編碼,設(shè)置字段相應(yīng)的屬性
view plaincopy to clipboardprint?
<input id='cusername' name='username' size='25' class='required' minlength='2'/>
<input id='cemail' name='email' size='25' class='required email'/>
<textarea id='ccomment' name='comment' cols='25' class='required'/>
<input id='cusername' name='username' size='25' class='required' minlength='2'/>
<input id='cemail' name='email' size='25' class='required email'/>
<textarea id='ccomment' name='comment' cols='25' class='required'/>
將所有的驗(yàn)證規(guī)則寫到class屬性里:
在實(shí)際的開發(fā)中,有的時(shí)候?qū)Ⅱ?yàn)證規(guī)則寫到class=’required email’有的時(shí)候?qū)懙絤inlength=’2’里面,這樣非常的不方便,有沒(méi)有一種方式可以將所有的驗(yàn)證規(guī)則放到一個(gè)地方去呢?這個(gè)答案是肯定的.jQuery充分考慮到了這一點(diǎn),我們可以通過(guò)另外一個(gè)JavaScript庫(kù)來(lái)將所有的驗(yàn)證規(guī)則放到一個(gè)class文件當(dāng)中去.這樣就大大方面了對(duì)驗(yàn)證規(guī)則的管理.
1) 在下載的\jquery-validate\lib文件夾下面找到j(luò)query.metadata.js.放到項(xiàng)目當(dāng)中,然后引入該jQuery插件.jquery.metadate.js是一個(gè)支持固定格式解析的jQuery插件,Validation插件將其很好的融合到驗(yàn)證規(guī)則編碼當(dāng)中.
view plaincopy to clipboardprint?
<mce:script type="text/javascript" src="jquery.metadata.js" mce_src="jquery.metadata.js"></mce:script>
<mce:script type="text/javascript" src="jquery.metadata.js" mce_src="jquery.metadata.js"></mce:script>
2) 改變調(diào)用的驗(yàn)證方法
view plaincopy to clipboardprint?
<mce:script type='text/javascript'><!--
$(document).ready(function(){
//確定那個(gè)表單進(jìn)行驗(yàn)證(改變調(diào)用的驗(yàn)證方法)
$('#commentForm').validate({meta: "validate"});
});
// --></mce:script>
<mce:script type='text/javascript'><!--
$(document).ready(function(){
//確定那個(gè)表單進(jìn)行驗(yàn)證(改變調(diào)用的驗(yàn)證方法)
$('#commentForm').validate({meta: "validate"});
});
// --></mce:script>
3) 將所有的驗(yàn)證規(guī)則都通過(guò)類似{validate:{required:true,email:true}}的形式,寫到class屬性當(dāng)中,詳細(xì)的HTML代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery之驗(yàn)證插件</title>
<script type='text/javascript' src='jquery-1.3.2.js'></script>
<!-- 引入了jQuery庫(kù)之后,繼續(xù)引入validation插件 -->
<script type='text/javascript' src='jquery.validate.js'></script>
<!-- 引入一個(gè)新的jQuery插件 -->
<script type="text/javascript" src='jquery.metadata.js'></script>
<style type='text/css'>
*{font-family:Verdana;font-size:96%;}
label.error{float:none;color:red;padding-left:.5em;vertical-align:top;}
p{clear:both;}
.submit{margin-left:12em;}
em{font-weight:bold;vertical-align:top;}
</style>
<script type='text/javascript'>
$(document).ready(function(){
//確定那個(gè)表單進(jìn)行驗(yàn)證(改變調(diào)用的驗(yàn)證方法)
$('#commentForm').validate({meta: "validate"});
});
</script>
</head>
<body>
<form class='cmxform' id='commentForm' method='get' action='#'>
<fieldset>
<legend>一個(gè)簡(jiǎn)單的帶有提示的評(píng)論例子</legend>
<p>
<label for='cusername'>姓名</label><em>*</em>
<input id='cusername' name='username' size='25' class='{validate:{required:true,minlength:2}}'/>
</p>
<p>
<label for='cemail'>電子郵件</label><em>*</em>
<input id='cemail' name='email' size='25' class='{validate:{required:true,email:true}}'/>
</p>
<p>
<label for='curl'>網(wǎng)址</label><em>*</em>
<input id='curl' name='url' size='25' class='{validate:{url:true}}' value=''/>
</p>
<p>
<label for='ccomment'>你的評(píng)論</label><em>*</em>
<textarea id='ccomment' name='comment' cols='25' class='{validate:{required:true}}'></textarea>
</p>
<p>
<input class='submit' type='submit' value='提交'>
</p>
</fieldset>
</form>
</body>
</html>
將驗(yàn)證行為和HTML結(jié)構(gòu)完全脫離的一種驗(yàn)證寫法:
上面的兩種寫法,一種是通過(guò)給標(biāo)簽添加屬性來(lái)完成驗(yàn)證,一種是通過(guò)jquery.metadate.js的幫助將所有的驗(yàn)證規(guī)則添加到class屬性中,都沒(méi)有符合jQuery提倡的”行為和操作分離”的一個(gè)原則,下面的方法就補(bǔ)足了這個(gè)缺陷,可以讓HTML結(jié)構(gòu)和驗(yàn)證規(guī)則很好的分離出來(lái)
HTML代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery之驗(yàn)證插件</title>
<script type='text/javascript' src='jquery-1.3.2.js'></script>
<!-- 引入了jQuery庫(kù)之后,繼續(xù)引入validation插件 -->
<script type='text/javascript' src='jquery.validate.js'></script>
<style type='text/css'>
*{font-family:Verdana;font-size:96%;}
label.error{float:none;color:red;padding-left:.5em;vertical-align:top;}
p{clear:both;}
.submit{margin-left:12em;}
em{font-weight:bold;vertical-align:top;}
</style>
<script type='text/javascript'>
$(document).ready(function(){
$('#commentForm').validate({
rules:{
username:{
required:true,
minlength:3
},
email:{
required:true,
email:true
},
url:"url",
comment:"required"
}
})
});
</script>
</head>
<body>
<form class='cmxform' id='commentForm' method='get' action='#'>
<fieldset>
<legend>一個(gè)簡(jiǎn)單的帶有提示的評(píng)論例子</legend>
<p>
<label for='cusername'>姓名</label><em>*</em>
<input id='cusername' name='username' size='25' />
</p>
<p>
<label for='cemail'>電子郵件</label><em>*</em>
<input id='cemail' name='email' size='25' />
</p>
<p>
<label for='curl'>網(wǎng)址</label><em>*</em>
<input id='curl' name='url' size='25' value=''/>
</p>
<p>
<label for='ccomment'>你的評(píng)論</label><em>*</em>
<textarea id='ccomment' name='comment' cols='25'></textarea>
</p>
<p>
<input class='submit' type='submit' value='提交'>
</p>
</fieldset>
</form>
</body>
</html>
在這種”HTML和驗(yàn)證完全分離”的驗(yàn)證規(guī)則寫法的步驟如下:
1) 在$(“#ccommentForm”).validate()方法中增加rules屬性
2) 通過(guò)每個(gè)字段的name屬性來(lái)匹配驗(yàn)證規(guī)則
3) 定義驗(yàn)證規(guī)則,比如required:true,email:true,minlength:2等等.
將默認(rèn)的英文驗(yàn)證信息變成中文:
validation插件默認(rèn)的驗(yàn)證信息是英文的,要想將validation驗(yàn)證插件給出的驗(yàn)證信息變成中文就可以到j(luò)query-validate\localization文件夾下面找到messages_cn.js文件,這個(gè)就是中文的驗(yàn)證信息庫(kù),我們只需要在代碼中將這個(gè)文件導(dǎo)入就可以實(shí)現(xiàn)中文驗(yàn)證信息的輸出了.在jquery-validate\localization這個(gè)文件夾下面,還有很多種語(yǔ)言,我們可以選擇適當(dāng)?shù)恼Z(yǔ)言引入到我們的項(xiàng)目當(dāng)中,實(shí)現(xiàn)提示信息的本地化.
view plaincopy to clipboardprint?
<!-- 引入中文驗(yàn)證信息庫(kù) -->
<mce:script type='text/javascript' src="messages_cn.js" mce_src="messages_cn.js"></mce:script>
<!-- 引入中文驗(yàn)證信息庫(kù) -->
<mce:script type='text/javascript' src="messages_cn.js" mce_src="messages_cn.js"></mce:script>
改變千篇一律的驗(yàn)證信息:
validaion驗(yàn)證插件可以非常方便的進(jìn)行自定義驗(yàn)證規(guī)則,這樣可以用來(lái)代替千篇一律的驗(yàn)證信息,具體修改好的HTML代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery之驗(yàn)證插件</title>
<script type='text/javascript' src='jquery-1.3.2.js'></script>
<!-- 引入了jQuery庫(kù)之后,繼續(xù)引入validation插件 -->
<script type='text/javascript' src='jquery.validate.js'></script>
<!-- 引入中文驗(yàn)證信息庫(kù) -->
<script type='text/javascript' src='messages_cn.js'></script>
<!-- 要將所有的驗(yàn)證規(guī)則放到css標(biāo)簽當(dāng)中去,就要引入metadate.js -->
<script type='text/javascript' src='jquery.metadata.js'></script>
<style type='text/css'>
*{font-family:Verdana;font-size:96%;}
label.error{float:none;color:red;padding-left:.5em;vertical-align:top;}
p{clear:both;}
.submit{margin-left:12em;}
em{font-weight:bold;vertical-align:top;}
</style>
<script type='text/javascript'>
$(document).ready(function(){
$('#commentForm').validate({meta:"validate"});
});
</script>
</head>
<body>
<form class='cmxform' id='commentForm' method='get' action='#'>
<fieldset>
<legend>一個(gè)簡(jiǎn)單的帶有提示的評(píng)論例子</legend>
<p>
<label for='cusername'>姓名</label><em>*</em>
<input id='cusername' name='username'
class="{validate:{required:true,minlength:2,messages:{
required:'姓名是必須要輸入的',
minlength:'請(qǐng)輸入不少于兩個(gè)字符的姓名'}}}"
size='25' />
</p>
<p>
<label for='cemail'>電子郵件</label><em>*</em>
<input id='cemail' name='email'
class="{validate:{required:true,email:true,messages:{
required:'郵箱是必須要輸入的',
email:'請(qǐng)輸入符合格式的Email地址'}}}"
size='25' />
</p>
<p>
<label for='curl'>網(wǎng)址</label><em>*</em>
<input id='curl' name='url'
class="{validate:{url:true,messages:{
url:'您的URL地址的輸入不符合要求'}}}"
size='25' value=''/>
</p>
<p>
<label for='ccomment'>你的評(píng)論</label><em>*</em>
<textarea id='ccomment' name='comment'
class="{validate:{
required:true,messages:{required:'多少也寫點(diǎn)評(píng)論哦'}}}"
cols='25'></textarea>
</p>
<p>
<input class='submit' type='submit' value='提交'>
</p>
</fieldset>
</form>
</body>
</html>
具體來(lái)說(shuō),上面的代碼就是在class的屬性中增加了類似messages:{required:’’,email:’’}形式的一塊代碼,這樣就可以顯示我們自定義的驗(yàn)證信息了.
自己來(lái)定義表單驗(yàn)證的業(yè)務(wù)規(guī)則:
通常在開發(fā)項(xiàng)目中,驗(yàn)證規(guī)則與實(shí)際的業(yè)務(wù)邏輯是息息相關(guān)的,一個(gè)好的驗(yàn)證插件必須要支持自定義驗(yàn)證機(jī)制,當(dāng)然jQuery就提供了多種機(jī)制來(lái)滿足用戶的業(yè)務(wù)需要.
我們添加以下代碼到上面的HTML代碼中,方便進(jìn)行驗(yàn)證碼的功能實(shí)現(xiàn).
view plaincopy to clipboardprint?
<p>
<label for='cvalcode'>驗(yàn)證碼</label>
<input id='cvalcode' name='valcode' size='25' value=''/>=7+9
</p>
<p>
<label for='cvalcode'>驗(yàn)證碼</label>
<input id='cvalcode' name='valcode' size='25' value=''/>=7+9
</p>
為了實(shí)現(xiàn)”驗(yàn)證碼”的功能,我們需要以下幾個(gè)步驟:
1) 自定義一個(gè)驗(yàn)證規(guī)則
view plaincopy to clipboardprint?
$.validator.addMethod(
"formula", //驗(yàn)證方法的名稱
function(value,element,param){ //驗(yàn)證規(guī)則
return value==eval(param);
},
'請(qǐng)輸入正確的結(jié)果' //提示驗(yàn)證信息
);
$.validator.addMethod(
"formula", //驗(yàn)證方法的名稱
function(value,element,param){ //驗(yàn)證規(guī)則
return value==eval(param);
},
'請(qǐng)輸入正確的結(jié)果' //提示驗(yàn)證信息
);
2) 在代碼中引用以上驗(yàn)證規(guī)則
view plaincopy to clipboardprint?
$('#commentForm').validate({
rules:{
username:{
required:true,
minlength:3
},
email:{
required:true,
email:true
},
url:"url",
comment:"required",
valcode:{formula:"7+9"}
}
})
本文來(lái)自CSDN博客,轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://blog.csdn.net/ziwen00/archive/2009/09/14/4551346.aspx
xtype Class
基本組件:
box Ext.BoxComponent 具有邊框?qū)傩缘慕M件
button Ext.Button 按鈕
colorpalette Ext.ColorPalette 調(diào)色板
component Ext.Component 組件
container Ext.Container 容器
cycle Ext.CycleButton
dataview Ext.DataView 數(shù)據(jù)顯示視圖
datepicker Ext.DatePicker 日期選擇面板
editor Ext.Editor 編輯器
editorgrid Ext.grid.EditorGridPanel 可編輯的表格
grid Ext.grid.GridPanel 表格
paging Ext.PagingToolbar 工具欄中的間隔
panel Ext.Panel 面板
progress Ext.ProgressBar 進(jìn)度條
splitbutton Ext.SplitButton 可分裂的按鈕
tabpanel Ext.TabPanel 選項(xiàng)面板
treepanel Ext.tree.TreePanel 樹
viewport Ext.ViewPort 視圖
window Ext.Window 窗口
工具欄組件:
toolbar Ext.Toolbar 工具欄
tbbutton Ext.Toolbar.Button 按鈕
tbfill Ext.Toolbar.Fill 文件
tbitem Ext.Toolbar.Item 工具條項(xiàng)目
tbseparator Ext.Toolbar.Separator 工具欄分隔符
tbspacer Ext.Toolbar.Spacer 工具欄空白
tbsplit Ext.Toolbar.SplitButton 工具欄分隔按鈕
tbtext Ext.Toolbar.TextItem 工具欄文本項(xiàng)
表單及字段組件:
form Ext.FormPanel Form 面板
checkbox Ext.form.Checkbox checkbox 錄入框
combo Ext.form.ComboBox combo 選擇項(xiàng)
datefield Ext.form.DateField 日期選擇項(xiàng)
field Ext.form.Field 表單字段
fieldset Ext.form.FieldSet 表單字段組
hidden Ext.form.Hidden 表單隱藏域
htmleditor Ext.form.HtmlEditor html 編輯器
numberfield Ext.form.NumberField 數(shù)字編輯器
radio Ext.form.Radio 單選按鈕
textarea Ext.form.TextArea 區(qū)域文本框
textfield Ext.form.TextField 表單文本框
timefield Ext.form.TimeField 時(shí)間錄入項(xiàng)
trigger Ext.form.TriggerField 觸發(fā)錄入項(xiàng)
只要ajax每次請(qǐng)求的地址不一樣就可以的。
原文地址:http://yaofeng911.javaeye.com/blog/379705jQuery Load樣本代碼:
$(document).ready(function(){$("#labels").load("/blog/categories/labels.html");//在頁(yè)面裝載時(shí),在ID為#labels的DOM元素里插入labels.html的內(nèi)容。
});
當(dāng)我更新了labels.html
以后,在IE7里load方法仍舊在使用舊的labels.html
,就算我按刷新鍵也不管用。好在jQuery提供一個(gè)防止ajax使用緩存的方法,把下面的語(yǔ)句加在head
的javascript文件里,就可以解決問(wèn)題。
$.ajaxSetup ({cache: false //關(guān)閉AJAX相應(yīng)的緩存});
此外我再介紹幾種方法解決緩存的方法。注意:我沒(méi)有在jQuery load
的問(wèn)題上測(cè)試過(guò),這些方法僅供參考!
1.更改文件名,比如把labels.html
改成lables_new.html
,但是這是沒(méi)有辦法的辦法,一般沒(méi)有人這么做。
2.在labels.html
后加上特定時(shí)間,比如lables.html?20081116
。在實(shí)際工作中,在我更新css/javascript文件后,我都是用這種辦法來(lái)防止文件被緩存。
3.在labels.html
文件的頂部加入以下聲明:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache"><META HTTP-EQUIV="Expires" CONTENT="-1">
4.load
函數(shù)不僅可以調(diào)用HTML,也可以調(diào)用script,比如labels.php
,可以在php文件里使用header
函數(shù):
");<?php
Cache-Control: no-cache, must-revalidate
?>
package com.founder.cst.action;
import Java.util.ArrayList;
import Java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BasicDynaBean;
import org.apache.commons.beanutils.BasicDynaClass;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.jmesa.core.filter.MatcherKey;
import org.jmesa.facade.TableFacade;
import org.jmesa.facade.TableFacadeFactory;
import org.jmesa.view.html.component.HtmlTable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.founder.cst.common.StringFilterMatcher;
@Controller
@RequestMapping
public class DynaController {
@RequestMapping
public String books(final HttpServletRequest request, HttpServletResponse response, ModelMap model){
DynaClass bookClass = createBasicDynaClass();
try {
List<DynaBean> results = new ArrayList<DynaBean>();
DynaBean book11 = bookClass.newInstance();
book11.set("id", "1");
book11.set("name", "Spring");
book11.set("price", "18.29");
results.add(book11);
DynaBean book22 = bookClass.newInstance();
book22.set("id", "2");
book22.set("name", "Hibernate");
book22.set("price", "12.29");
results.add(book22);
DynaBean book33 = bookClass.newInstance();
book33.set("id", "3");
book33.set("name", "Python");
book33.set("price", "17.32");
results.add(book33);
TableFacade tableFacade = TableFacadeFactory.createTableFacade("booksTable", request);
tableFacade.setColumnProperties("id", "name", "price");
tableFacade.setMaxRows(10);
tableFacade.setMaxRowsIncrements(10, 20, 30);
tableFacade.setItems(results);
HtmlTable table = (HtmlTable) tableFacade.getTable();
table.getTableRenderer().setWidth("558px");
table.getRow().setUniqueProperty("id");
String html = tableFacade.render();
model.addAttribute("html", html);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "books";
}
public DynaClass createBasicDynaClass() {
DynaClass dynaClass = null;
//create basic field for dynaClass
DynaProperty[] dynaProps = new DynaProperty[3];
dynaProps[0] = new DynaProperty("id");
dynaProps[1] = new DynaProperty("name", String.class);
dynaProps[2] = new DynaProperty("price", String.class);
//create map filed for dynaClass
dynaClass = new BasicDynaClass("first", BasicDynaBean.class, dynaProps);
return dynaClass;
}
}
下面第二種:
@RequestMapping
public String bookslist(final HttpServletRequest request, HttpServletResponse response, ModelMap model){
List<Map<String, String>> books = new ArrayList<Map<String, String>>();
Map<String, String> book1 = new HashMap<String, String>();
book1.put("id", "1");
book1.put("name", "Spring");
book1.put("price", "18.29");
books.add(book1);
Map<String, String> book2 = new HashMap<String, String>();
book2.put("id", "2");
book2.put("name", "Hibernate");
book2.put("price", "28.98");
books.add(book2);
Map<String, String> book3 = new HashMap<String, String>();
book3.put("id", "3");
book3.put("name", "Python");
book3.put("price", "38.22");
books.add(book3);
model.addAttribute("books", books);
return "booklist";
}
/*
* Copyright 2004 original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jmesa.util;
import Java.util.Collection;
import Java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* General utilities to process the Collecton of Beans or the Collection of
* Maps. Most methods wrap or add value to the commons Beanutils.
*
* @since 2.1
* @author Jeff Johnston
*/
public class ItemUtils {
private static final Logger logger = LoggerFactory.getLogger(ItemUtils.class);
public static final String JMESA_ITEM = "jmesa-item";
private ItemUtils() {
// hide constructor
}
/**
* Get the value from the Bean or Map by property.
*
* @param item The Bean or Map.
* @param property The Bean attribute or Map key.
* @return The value from the Bean or Map.
*/
public static Object getItemValue(Object item, String property) {
Object itemValue = null;
try {
if (item instanceof Map) {
itemValue = ((Map<?, ?>) item).get(property);
if (itemValue != null) {
return itemValue;
}
// ports such as the tags will store the original bean
Object bean = ((Map<?, ?>) item).get(JMESA_ITEM); if (bean == null) {
logger.debug("the map does not have property " + property);
return null;
}
itemValue = getItemValue(bean, property);
} else {
itemValue = PropertyUtils.getProperty(item, property);
}
} catch (Exception e) {
logger.debug("item class " + item.getClass().getName() + " does not have property " + property);
}
return itemValue;
}
/**
* Get the Class for the property.
*
* @param items The Collection of Beans or Maps.
* @param property The Bean attribute or Map key.
* @return The Class for the property.
*/
public static Class<?> getPropertyClassType(Collection<?> items, String property)
throws Exception {
Object item = items.iterator().next();
if (item instanceof Map) {
for (Object object : items) {
Map map = (Map) object;
Object val = map.get(property);
if (val == null) {
continue;
}
return val.getClass();
}
}
return PropertyUtils.getPropertyType(item, property);
}
}
import Java.util.List;
import org.jmesa.view.ViewUtils;
import org.jmesa.view.component.Row;
import org.jmesa.view.html.HtmlBuilder;
import org.jmesa.view.html.HtmlSnippetsImpl;
import org.jmesa.view.html.component.HtmlTable;
import org.jmesa.view.html.toolbar.AbstractToolbar;
import org.jmesa.view.html.toolbar.MaxRowsItem;
import org.jmesa.view.html.toolbar.ToolbarItem;
import org.jmesa.view.html.toolbar.ToolbarItemType;
public class CustomToolbar extends AbstractToolbar {
@Override
public String render() {
//addToolbarItem(ToolbarItemType.PAGE_NUMBER_ITEMS);
addToolbarItem(ToolbarItemType.FIRST_PAGE_ITEM);
addToolbarItem(ToolbarItemType.PREV_PAGE_ITEM);
addToolbarItem(ToolbarItemType.NEXT_PAGE_ITEM);
addToolbarItem(ToolbarItemType.LAST_PAGE_ITEM);
addToolbarItem(ToolbarItemType.SEPARATOR);
MaxRowsItem maxRowsItem = (MaxRowsItem) addToolbarItem(ToolbarItemType.MAX_ROWS_ITEM);
if (getMaxRowsIncrements() != null) {
maxRowsItem.setIncrements(getMaxRowsIncrements());
}
boolean exportable = ViewUtils.isExportable(getExportTypes());
if (exportable) {
addToolbarItem(ToolbarItemType.SEPARATOR);
addExportToolbarItems(getExportTypes());
}
Row row = getTable().getRow();
List columns = row.getColumns();
boolean filterable = ViewUtils.isFilterable(columns);
if (filterable) {
addToolbarItem(ToolbarItemType.SEPARATOR);
addToolbarItem(ToolbarItemType.FILTER_ITEM);
addToolbarItem(ToolbarItemType.CLEAR_ITEM);
}
HtmlSnippetsImpl statusBar = new HtmlSnippetsImpl((HtmlTable)this.getTable(), this, this.getCoreContext());
// super render
HtmlBuilder html = new HtmlBuilder();
html.table(2).border("0").cellpadding("0").cellspacing("1").close();
html.tr(3).close();
html.td(4).close();
html.append(statusBar.statusBarText());
html.tdEnd();
for (ToolbarItem item : this.getToolbarItems()) {
html.td(4).close();
html.append(item.getToolbarItemRenderer().render());
html.tdEnd();
}
html.trEnd(3);
html.tableEnd(2);
html.newline();
html.tabs(2);
return html.toString();
}
}
First we need to set the max rows to the total amount of items that we want to display.
tableFacade.setMaxRows(items.size());
Then we need to implement a custom view. If you compare this view to the HtmlView in the API you can see that I just removed two lines of code. One to remove the toolbar and one for the status bar.
public class CustomView extends AbstractHtmlView {
public Object render() {
HtmlSnippets snippets = getHtmlSnippets();
HtmlBuilder html = new HtmlBuilder();
html.append(snippets.themeStart());
html.append(snippets.tableStart());
html.append(snippets.theadStart());
html.append(snippets.filter());
html.append(snippets.header());
html.append(snippets.theadEnd());
html.append(snippets.tbodyStart());
html.append(snippets.body());
html.append(snippets.tbodyEnd());
html.append(snippets.footer());
html.append(snippets.tableEnd());
html.append(snippets.themeEnd());
html.append(snippets.initJavascriptLimit());
return html.toString();
}
}
Lastly, just plug your custom view into the TableFacade.
tableFacade.setView(new CustomView());
<jmesa:tableFacade view="com.mycompany.CustomView">
//for checkbox column
HtmlColumn chkbox = table.getRow().getColumn("chkbox");
chkbox.getCellRenderer().setWorksheetEditor(new CheckboxWorksheetEditor());
chkbox.setTitle(" ");
chkbox.setFilterable(false);
chkbox.setSortable(false);
//render
String html = tableFacade.render();
搜索與參數(shù)表示的對(duì)象匹配的元素,并返回相應(yīng)元素的索引值。如果找到了匹配的元素,從0開始返回;如果沒(méi)有找到匹配的元素,返回-1。
data(elem):為頁(yè)面對(duì)象添加唯一標(biāo)識(shí)。
data(name, value):將數(shù)據(jù)保存在元素的一個(gè)key里面。$("#box").data("shape","rectangle")。
data(name):獲取值。$("#box").data("shape") //"rectangle"。
removeData(name):刪除通過(guò)data()方法賦予的值。$("#box").removeData("shape")。
為所有匹配的元素設(shè)置一個(gè)計(jì)算的屬性值。不提供值,而是提供一個(gè)函數(shù),由這個(gè)函數(shù)計(jì)算的值作為屬性值。
檢查當(dāng)前的元素是否含有某個(gè)特定的類,如果有,則返回true。這其實(shí)就是is("." + class)。
設(shè)置每一個(gè)匹配元素的值。在 jQuery 1.2, 這也可以為select元件賦值。參數(shù)val(String)要設(shè)置的值。
check,select,radio等都能使用為之賦值。參數(shù)val(Array<String>)用于 check/select 的值。
選取一個(gè)匹配的子集。
把與表達(dá)式匹配的元素添加到j(luò)Query對(duì)象中。這個(gè)函數(shù)可以用于連接分別與兩個(gè)表達(dá)式匹配的元素結(jié)果集。
參數(shù)expr(String, DOMElement, Array<DOMElement>)用于匹配元素并添加的表達(dá)式字符串,或者用于動(dòng)態(tài)生成的HTML代碼,如果是一個(gè)字符串?dāng)?shù)組則返回多個(gè)元素。
查找當(dāng)前元素之后的所有元素。
取得一個(gè)包含匹配的元素集合中每一個(gè)元素緊鄰的前一個(gè)同輩元素的元素集合。
查找當(dāng)前元素之前所有的同輩元素。
將先前所選的加入當(dāng)前元素中。
將所有匹配的元素替換成指定的HTML或DOM元素。參數(shù)content(String, Element, jQuery):用于將匹配元素替換掉的內(nèi)容。
用匹配的元素替換掉所有 selector匹配到的元素。參數(shù)selector(選擇器)用于查找所要被替換的元素。
克隆匹配的DOM元素并且選中這些克隆的副本。設(shè)置參數(shù)[true]是對(duì)象的所有事件處理一并克隆。
獲取匹配元素在當(dāng)前視口的相對(duì)偏移。返回的對(duì)象包含兩個(gè)整形屬性:top 和 left。此方法只對(duì)可見(jiàn)元素有效。
返回Object{top,left}。
為每一個(gè)匹配元素的特定事件(像click)綁定一個(gè)一次性的事件處理函數(shù)。
在每個(gè)對(duì)象上,這個(gè)事件處理函數(shù)只會(huì)被執(zhí)行一次。其他規(guī)則與bind()函數(shù)相同。這個(gè)事件處理函數(shù)會(huì)接收到一個(gè)事件對(duì)象,可以通過(guò)它來(lái)阻止(瀏覽器)默認(rèn)的行為。如果既想取消默認(rèn)的行為,又想阻止事件起泡,這個(gè)事件處理函數(shù)必須返回false。
每次點(diǎn)擊時(shí)切換要調(diào)用的函數(shù)。函數(shù)數(shù)目可以是多個(gè)。
停止所有在指定元素上正在運(yùn)行的動(dòng)畫。如果隊(duì)列中有等待執(zhí)行的動(dòng)畫,他們將被馬上執(zhí)行。
queue:返回指向第一個(gè)匹配元素的隊(duì)列(將是一個(gè)函數(shù)數(shù)組。
queue(callback):在匹配的元素的動(dòng)畫隊(duì)列中添加一個(gè)函數(shù)。
queue(queue):將匹配元素的動(dòng)畫隊(duì)列用新的一個(gè)隊(duì)列來(lái)代替(函數(shù)數(shù)組)。
從動(dòng)畫隊(duì)列中移除一個(gè)隊(duì)列函數(shù)。
瀏覽器渲染引擎版本號(hào)。
當(dāng)前頁(yè)面中瀏覽器是否使用標(biāo)準(zhǔn)盒模型渲染頁(yè)面。
PS:以前很少用這些方法屬性,很多還不知道。這跟中文CHM版jQuery API不無(wú)關(guān)系,那本廣為流傳的中文版手冊(cè)已經(jīng)過(guò)時(shí),建議直接閱讀官方文檔。
$()取得頁(yè)面中的元素
$(document).ready(function(){
$('.poem-stanza').addClass('emphasized');
});
說(shuō)明:
$('.poem-stanza') //取得頁(yè)面中添加了類poem-stanza的元素
.addClass('emphasized'); //添加Css樣式,emphasized為類樣式
.removeClass();
第二章:選擇符
$(document).ready(function(){
//CSS選擇符
$('#selectedplays>li').addClass('horizontal'); //查找id為selectedplays元素的頂層子元素li,添加樣式
$('#selectedplays>li:not(.horizotal)').addClass('sublevel'); //查找id為selectedplays元素的頂層子元素li,并且沒(méi)有類horizotal
//XPath選擇符
$('a[@href^="mailto:"]').addClass('mailto'); //查找錨元素中屬性href以“mailto:”開頭的元素
$('a[@href$=".pdf"]').addClass('pdflink'); //查找錨元素中屬性href以“.pdf”結(jié)尾的元素
$('a[@href*="mysite.com"]').addClass('mysite'); //查找錨元素中屬性href中包含“mysite.com”的元素(任意位置)
//自定義選擇符
$('tr:odd').addClass('odd'); //查找奇數(shù)行
$('tr:even').addClass('even'); //查找偶數(shù)行
//注::odd()和:even()選擇符使用的都是Javascript本身的從0開始得編號(hào)方式。表格的第1行編號(hào)為0(偶數(shù)),而第2行編號(hào)為1(奇數(shù))
$('td:contains("Henry")').addClass('highlight'); //查找td中包含"Henry"的
//DOM遍歷方法
$('th').parent().addClass('tableheading'); //查找th的父元素即標(biāo)題行
$('tr:not([th]):even').addClass('even'); //查找tr元素中不包含子為th的,并且是偶數(shù)行
$('tr:not([th]):odd').addClass('odd');
$('td:contains("Henry")').next().addClass('highlight'); //查找td中包含“Henry”的單元格的下一個(gè)單元格
$('td:contains("Comedy")').siblings().addClass('highlight'); //查找td中包含“Comedy”的同級(jí)單元格
$('td:contains("Comedy")').parent().find('td:gt(0)').addClass('highlight');
//查找td中包含“Comedy”的父,再去查找td單元格編號(hào)大于0的單元格
$('td:contains("Comedy)').parent().find('td').not(':contains("Comedy")').addClass('highlight');
//查找td中包含“Comedy”的父,再去查找td單元格不包含“Comedy”的單元格
//訪問(wèn)DOM元素
var tag = $('#myelement').get(0).tagName;
});
第三章:事件――扣動(dòng)扳機(jī)
綁定事件:
.bind(‘click’,function(){})
$(‘#switcher-large’).bind(‘click’,function(){…});給id為switcher-large的元素綁定click事件
可簡(jiǎn)寫為
$(‘#switcher-large’).click(function(){…});
方法:
.toggle(function(){},function(){})
接受兩個(gè)參數(shù)(都是函數(shù))第一次點(diǎn)擊調(diào)用第一個(gè)函數(shù),第二次點(diǎn)擊調(diào)用第二個(gè)
$(‘#switcher h3’).toggle(function(){
$(‘#switcher .button’).addClass(‘hidden’);
},function(){
$(‘#switcher .button’).removeClass(‘hidden’);
});
.toggleClass()是一種跟優(yōu)雅得方案,但對(duì)于交替執(zhí)行的操作而言,.toggle()的適用性更強(qiáng)
$(‘#switcher h3’).click(function(){
$(‘#switcher .button’).toggleClass(‘hidden’); //自動(dòng)檢查該類是否存在
});
.hover(function(){},function(){})
接受兩個(gè)函數(shù)參數(shù),第一個(gè)指針進(jìn)入,第二個(gè)指針離開
$(‘#switcher .button’).hover(function(){
$(this).addClass(‘hover’);
},function(){
$(this).removeClass(‘hover’);
});
.unbind(‘click’)
移除事件
.trigger(‘click’)
模擬用戶操作
$(‘#switcher’).trigger(‘click’); 模擬點(diǎn)擊了一次switcher
第四章:效果――為操作添加藝術(shù)性
1.修改內(nèi)聯(lián)CSS
語(yǔ)法:
.css(‘property’,’value’);
.css(‘property’:’value’,’property’:’value’);
用法:
var currentSize = $(‘div.speech’).css(‘fontSize’);//得到div.speech得字體大小
var num = parasFloat(currentSize,10); //將currentSize轉(zhuǎn)換為Float型
var unit = currentSize.slice(-2); //返回從指定的字符開始的一個(gè)子字符串,-2為倒數(shù)第二個(gè)
num *= 1.5;
$(‘div.speech’).css(‘fontSize’,num+unit); //設(shè)置樣式
2.基本的顯示和隱藏
.show();
.hide();
用法:
$(‘p:eq(1)’).hide(); //將第二個(gè)段落隱藏
3.效果和速度
指定顯示速度
3種:slow、normal和fast 時(shí)間:0.6、0,4、0.2。也可以指定.show(850)
$(‘p:eq(2)’).show(‘slow’);
淡入和淡出
.fadeIn(); //淡出
.fadeOut(); //淡出
$(‘p:eq(2)’).fadeIn(‘slow’);
4.多重效果
語(yǔ)句:.animate({param1:’value1’,parame2:’value2’},speed,function(){回調(diào)});
用法:$(‘p:eq(1)’).animate({height:’show’,width:’show’,opacity:’show’},’slow’);
這里使用簡(jiǎn)寫的show將高度、寬度回復(fù)到被隱藏之前的值
5.并發(fā)與排隊(duì)效果
處理一組元素
$(‘div.buttont’).animate({left:650},’slow’).animate({height:38},’slow’);
先移動(dòng)到left為650的位置,在將高度設(shè)置為38
$(‘div.button’)
.fadeTo(‘slow’,0.5) //先淡化
.animate({left:650},’slow’) //在移動(dòng)
.fadeTo(‘slow’,1.0) //在淡出
.slideUp(‘slow’) //最后滑到上方隱藏
注意:排隊(duì)不適用于其他的非效果方法,例如:.css()
處理多組元素
$(‘p:eq(2)’).slideUp(‘slow’).next().slideDown(‘slow’); 段落3向上滑出,同時(shí)段落4向下滑入
回調(diào)函數(shù):
Var $thisPara = $(‘p:eq(2)’);
$(‘p:eq(2)’).next().slideDown(‘slow’,function(){
$thisPara.slideUp(‘slow’);
});
段落4下滑完成后,段落3才開始上滑
第五章:DOM操作-基于命令改變頁(yè)面
1.操作屬性
非css屬性
$(document).ready(function(){
$('div.chapter a[@href*=wikipedia]').each(function(index){
var $thisLink = $(this);
$thisLink.attr({
'rel': 'external',
'id': 'wikilink-' + index,
'title': 'learn more about ' + $thisLink.text() + ' at wikipedia'
});
});
});
//遍歷div.chapter 下面所以錨元素href中包含wikipedia,為其添加屬性
深入理解$()工廠函數(shù)
$('<a href="#top">back to top</a>'); 創(chuàng)建新元素
2.插入新元素
.insertBefore()
.before()
作用相同,區(qū)別取決于將它們與其他方法進(jìn)行連綴
.insertAfter()
.after()
// $('div.chapter p').after('<a href="#top">back to top</a>');
// $('div.chapter p').before('<a href="#top">back to top</a>');
$('<a href="#aaa">back to top</a>').insertAfter('div.chapter p');
$('<a id="aaa" name="top"></a>').prependTo('body');
.perpendTo插入了作為目標(biāo)的錨
// $('<a href="#top">back to top</a>').insertBefore('div.chapter p');
3.移動(dòng)元素
$('span.footnote').insertBefore('#footer');
將span中類為footnote的插入到id為footer的前面
標(biāo)注、編號(hào)和鏈接到上下文
$('span.footnote').each(function(index){
$(this)
.before('<a href="#foot-note-' + (index+1) +
'" id="context-' + (index+1) +
'" class="context"><sup>' + (index+1) +
'</sup></a>');
});
$('span.footnote').insertBefore('#footer');
遍歷span.footnote,在各個(gè)元素前加標(biāo)注后,在將span.footnote添加到#footer前
插入腳注
$('<ol id="notes"></ol>').insertAfter('div.chapter');
$('span.footnote').each(function(index){
$(this)
.before('<a href="#foot-note-' + (index+1) +
'" id="context-' + (index+1) +
'" class="context"><sup>' + (index+1) +
'</sup></a>')
.appendTo('#notes')
.append(' (<a href="#context-'+(index+1)+'">context</a>)');
});
先創(chuàng)建一個(gè)ol元素notes,并添加到div.chapter后面,遍歷span.footnote,先添加標(biāo)注,然后通過(guò)appendTo其添加到ol末尾,最后又通過(guò)append添加一個(gè)錨元素。
4.包裝元素
.wrap()
.wrap('<li id="foot-note-' + (index+1) + '"></li>')
5.復(fù)制元素
.clone()
$('div.chapter p:eq(0)').clone().insertBefore('div.chapter');
將div.chapter中得第一段復(fù)制后插入在div.chapter前面
深度復(fù)制
$('div.chapter p:eq(0)').clone(false)
只復(fù)制結(jié)構(gòu),內(nèi)部的文本沒(méi)有復(fù)制過(guò)來(lái),因?yàn)槲谋疽彩荄OM節(jié)點(diǎn)
通過(guò)復(fù)制創(chuàng)建突出引用
var $parentParagraph = $(this).parent('p');
$parentParagraph.css('position','relative');
$(this).clone()
.addClass('pulled')
.prependTo($parentParagraph);
修飾突出引用
$clonedCopy.addClass('pulled')
.find('span.drop')
.html('…')
.end()
.prependTo($parentParagraph)
.wrap('<div class="pulled-wrapper"></div>');
var clonedText = $clonedCopy.text();
$clonedCopy.html(clonedText);
第六章:AJAX 讓網(wǎng)站與時(shí)俱進(jìn)
1.基于請(qǐng)求加載數(shù)據(jù)
追加HTML
//載入遠(yuǎn)程 HTML 文件代碼并插入至 DOM 中
$('#dictionary').load('a.html',function(){
Alert(“加載完畢!”);//回調(diào)函數(shù)
})
操作JavaScript對(duì)象
JSON:
[
{
"term": "BACKBITE",
"part": "v.t.",
"definition": "To speak of a man as you find him when he can't find you."
},
{
"term": "BEARD",
"part": "n.",
"definition": "The hair that is commonly cut off by those who justly execrate the absurd Chinese custom of shaving the head."
}
]
JQuery:
$.getJSON('b.json',function(data){ //通過(guò) HTTP GET 請(qǐng)求載入 JSON 數(shù)據(jù)
$.each(data,function(entryIndex,entry){
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="pare">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
if(entry['quote']){
html += '<div class="quote">';
$.each(entry['quote'],function(lineIndex,line){
html += '<div class="quote-line">' + line + '</div>';
});
if(entry['author']){
html += '<div class="quote-author">' + entry['author'] + '</div>';
}
html += '</div>';
}
html += '</div>';
html += '</div>';
});
執(zhí)行腳本
通過(guò) HTTP GET 請(qǐng)求載入并執(zhí)行一個(gè) JavaScript 文件
$.getScript('c.js',function(){
Alert(“加載完畢”);//回調(diào)函數(shù)
});
加載XML文檔
//通過(guò)遠(yuǎn)程 HTTP GET 請(qǐng)求載入信息。
$.get('d.xml',function(data){
$(data).find('entry').each(function(){
var $entry = $(this);
var html = '<div class="entry">';
html += '<h3 class="term">' + $entry.attr('term') + '</h3>';
html += '<div class="part">' + $entry.attr('part') + '</div>';
html += '<div class="definition">'
html += $entry.find('definition').text();
var $quote = $entry.find('quote');
if($quote.length){
html += '<div class="quote">';
$quote.find('line').each(function(){
html += '<div class="quote-line">' + $(this).text() + '</div>';
});
if($quote.attr('author')){
html += '<div class="quote-author">' + $quote.attr('author') + '</div>';
}
html += '</div>';
}
html += '</div>';
html += '</div>';
$('#dictionary').append($(html));
});
});
2.選擇數(shù)據(jù)格式
3.向服務(wù)器傳遞數(shù)據(jù)
4.關(guān)注請(qǐng)求
方法:
.ajaxStart()
.ajaxStop()
當(dāng)AJAX請(qǐng)求開始且尚未進(jìn)行其他傳輸時(shí),會(huì)觸發(fā).ajaxStart()的回調(diào)函數(shù),相反,當(dāng)最后一次活動(dòng)請(qǐng)求終止時(shí),則會(huì)執(zhí)行通過(guò).ajaxStop()注冊(cè)的回調(diào)函數(shù)。
示例:
//當(dāng)請(qǐng)求時(shí),顯示#loading,結(jié)束時(shí),隱藏loading
$(document).ready(function(){
$('#loading').ajaxStart(function(){
$(this).show();
}).ajaxStop(function(){
$(this).hide();
});
});
5.Ajax和事件
限制函數(shù)綁定的作用域
$(document).ready(function(){
var bindBehaviors = function(scope){
$('h3',scope).click(function(){
$(this).toggleClass('highlighted');
});
};
bindBehaviors(this);
//這里的綁定作用域是document
$(document).ready(function(){
$('#letter-a .button').click(function(){
$('#dictionary').hide().load('a.html',function(){
bindBehaviors(this);
//這里的是文檔中的所以<h3>元素
$(this).fadeIn();
});
});
});
});
6.安全限制
jQuery is definitely my favourite Javascript Library and this ultimate jQuery Plugin List is for all other jQuery Lovers out there. At the moment there are about 240+ awesome Plugins in the List I’m sure that there are a lot of other plugins out there - so if you knew one that’s not in the list please post a comment and i will add it. Thanks!
Ajax File Upload
jQUploader
Multiple File Upload plugin
jQuery File Style
Styling an input type file
Progress Bar Plugin
jQuery Validation
Auto Help
Simple jQuery form validation
jQuery XAV - form validations
jQuery AlphaNumeric
Masked Input
TypeWatch Plugin
Text limiter for form fields
Ajax Username Check with jQuery
jQuery Combobox
jQuery controlled dependent (or Cascadign) Select List
Multiple Selects
Select box manipulation
Select Combo Plugin
jQuery - LinkedSelect
Auto-populate multiple select boxes
Choose Plugin (Select Replacement)
jQuery Form Plugin
jQuery-Form
jLook Nice Forms
jNice
Ping Plugin
Toggle Form Text
ToggleVal
jQuery Field Plugin
jQuery Form’n Field plugin
jQuery Checkbox manipulation
jTagging
jQuery labelcheck
Overlabel
3 state radio buttons
ShiftCheckbox jQuery Plugin
Watermark Input
jQuery Checkbox (checkboxes with imags)
jQuery SpinButton Control
jQuery Ajax Form Builder
jQuery Focus Fields
jQuery Time Entry
jQuery UI Datepicker
jQuery date picker plugin
jQuery Time Picker
Time Picker
ClickPick
TimePicker
Farbtastic jQuery Color Picker Plugin
Color Picker by intelliance.fr
jQuery Star Rating Plugin
jQuery Star Rater
Content rater with asp.net, ajax and jQuery
Half-Star Rating Plugin
Autocomplete Box
jQuery Suggest
jQuery Autocomplete
jQuery Autocomplete Mod
jQuery Autocomplete by AjaxDaddy
jQuery Autocomplete Plugin with HTML formatting
jQuery Autocompleter
AutoCompleter (Tutorial with PHP&MySQL)
quick Search jQuery Plugin
jTagEditor
WYMeditor
jQuery jFrame
Jeditable - edit in place plugin for jQuery
jQuery editable
jQuery Disable Text Select Plugin
Edit in Place with Ajax using jQuery
jQuery Plugin - Another In-Place Editor
TableEditor
tEditable - in place table editing for jQuery
jMedia - accessible multi-media embedding
JBEdit - Ajax online Video Editor
jQuery MP3 Plugin
jQuery Media Plugin
jQuery Flash Plugin
Embed QuickTime
SVG Integration
jQuery Multimedia Portfolio
jQuery YouTube Plugin
ThickBox
jQuery lightBox plugin
jQuery FancyBox
jQuery Multimedia Portfolio
jQuery Image Strip
jQuery slideViewer
jQuery jqGalScroll 2.0
jQuery - jqGalViewII
jQuery - jqGalViewIII
jQuery Photo Slider
jQuery Thumbs - easily create thumbnails
jQuery jQIR Image Replacement
jCarousel Lite
jQPanView
jCarousel
Interface Imagebox
Image Gallery using jQuery, Interface & Reflactions
simple jQuery Gallery
jQuery Gallery Module
EO Gallery
jQuery ScrollShow
jQuery Cycle Plugin
jQuery Flickr
jQuery Lazy Load Images Plugin
Zoomi - Zoomable Thumbnails
jQuery Crop - crop any image on the fly
Image Reflection
jQuery Plugin googlemaps
jMaps jQuery Maps Framework
jQmaps
jQuery & Google Maps
jQuery Maps Interface forr Google and Yahoo maps
jQuery J Maps - by Tane Piper
Tetris with jQuery
jQuery Chess
Mad Libs Word Game
jQuery Puzzle
jQuery Solar System (not a game but awesome jQuery Stuff)
jQuery Memory
UI/Tablesorter
jQuery ingrid
jQuery Grid Plugin
Table Filter - awesome!
TableEditor
jQuery Tree Tables
Expandable “Detail” Table Rows
Sortable Table ColdFusion Costum Tag with jQuery UI
jQuery Bubble
TableSorter
Scrollable HTML Table
jQuery column Manager Plugin
jQuery tableHover Plugin
jQuery columnHover Plugin
jQuery Grid
TableSorter plugin for jQuery
tEditable - in place table editing for jQuery
jQuery charToTable Plugin
jQuery Grid Column Sizing
jQuery Grid Row Sizing
Flot
jQuery Wizard Plugin
jQuery Chart Plugin
Bar Chart
Accessible Charts using Canvas and jQuery
jQuery Corner
jQuery Curvy Corner
Nifty jQuery Corner
Transparent Corners
jQuery Corner Gallery
Gradient Plugin
jQuery Spoiler plugin
Text Highlighting
Disable Text Select Plugin
jQuery Newsticker
Auto line-height Plugin
Textgrad - a text gradient plugin
LinkLook - a link thumbnail preview
pager jQuery Plugin
shortKeys jQuery Plugin
jQuery Biggerlink
jQuery Ajax Link Checker
Chili jQuery code highlighter plugin
jScroller
jQuery Plugin - Tooltip
jTip - The jQuery Tool Tip
clueTip
BetterTip
Flash Tooltips using jQuery
ToolTip
jQuery Tabs Plugin - awesome! [demo nested tabs]
another jQuery nested Tab Set example (based on jQuery Tabs Plugin)
jQuery idTabs
jdMenu - Hierarchical Menu Plugin for jQuery
jQuery SuckerFish Style
jQuery Plugin Treeview
treeView Basic
FastFind Menu
Sliding Menu
Lava Lamp jQuery Menu
jQuery iconDock
jVariations Control Panel
ContextMenu plugin
clickMenu
CSS Dock Menu
jQuery Pop-up Menu Tutorial
Sliding Menu
jQuery Plugin Accordion
jQuery Accordion Plugin Horizontal Way
haccordion - a simple horizontal accordion plugin for jQuery
Horizontal Accordion by portalzine.de
HoverAccordion
Accordion Example from fmarcia.info
jQuery Accordion Example
jQuery Demo - Expandable Sidebar Menu
Sliding Panels for jQuery
jQuery ToggleElements
Coda Slider
jCarousel
Accesible News Slider Plugin
Showing and Hiding code Examples
jQuery Easing Plugin
jQuery Portlets
AutoScroll
Innerfade
CodaSlider
UI/Draggables
EasyDrag jQuery Plugin
jQuery Portlets
jqDnR - drag, drop resize
Drag Demos
XSLT Plugin
jQuery Ajax call and result XML parsing
xmlObjectifier - Converts XML DOM to JSON
jQuery XSL Transform
jQuery Taconite - multiple Dom updates
RSS/ATOM Feed Parser Plugin
jQuery Google Feed Plugin
Wresize - IE Resize event Fix Plugin
jQuery ifixpng
jQuery pngFix
Link Scrubber - removes the dotted line onfocus from links
jQuery Perciformes - the entire suckerfish familly under one roof
Background Iframe
QinIE - for proper display of Q tags in IE
jQuery Accessibility Plugin
jQuery MouseWheel Plugin
jQuery Impromptu
jQuery Confirm Plugin
jqModal
SimpleModal
jQuery Style Switcher
JSS - Javascript StyleSheets
jQuery Rule - creation/manipulation of CSS Rules
jPrintArea
FlyDOM
jQuery Dimenion Plugin
jQuery Loggin
Metadata - extract metadata from classes, attributes, elements
Super-tiny Client-Side Include Javascript jQuery Plugin
Undo Made Easy with Ajax
JHeartbeat - periodically poll the server
Lazy Load Plugin
Live Query
jQuery Timers
jQuery Share it - display social bookmarking icons
jQuery serverCookieJar
jQuery autoSave
jQuery Puffer
jQuery iFrame Plugin
Cookie Plugin for jQuery
jQuery Spy - awesome plugin
Effect Delay Trick
jQuick - a quick tag creator for jQuery
Metaobjects
elementReady
原文地址: http://www.kollermedia.at/archive/2007/11/21/the-ultimate-jquery-plugin-list/
Lightbox JS 是一個(gè)簡(jiǎn)單而又謙恭的用來(lái)把圖片覆蓋在當(dāng)前頁(yè)面上的腳本. 它能被快速安裝并且運(yùn)作于所有流行的瀏覽器.
最新更新 Version 2.0
如何使用:
步驟 1 - 安裝
1、Lightbox v2.0 使用 Prototype 框架和 Scriptaculous 效果庫(kù). 你將需要外調(diào)這三個(gè) Javascript 文件在你的 header.
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
2、外調(diào) Lightbox CSS 文件 (或添加 Lightbox 樣式到你現(xiàn)行的樣式表中).
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
3、檢查 CSS 并確定調(diào)用的 prev.gif 和 next.gif 文件在正確的位置. 同樣要確定調(diào)用的 loading.gif 和 close.gif 文件及 lightbox.js 文件在正確的位置.
步驟 2 - 激活
1、添加 rel="lightbox" 屬性到任何一個(gè)鏈接標(biāo)簽去激活lightbox. 例如:
<a href="images/image-1.jpg" rel="lightbox" title="my caption">image #1</a>
可選擇項(xiàng): 使用 title 屬性加上說(shuō)明.
2、如果你有一套你想分組的相關(guān)圖片, 接著上一部并且又在 rel 屬性中添加一個(gè)帶方括號(hào)的組名. 例如:
<a href="images/image-1.jpg" rel="lightbox[roadtrip]">image #1</a>
<a href="images/image-2.jpg" rel="lightbox[roadtrip]">image #2</a>
<a href="images/image-3.jpg" rel="lightbox[roadtrip]">image #3</a>
3、沒(méi)有限定每個(gè)頁(yè)面的圖片組數(shù)量和每個(gè)圖片組圖片的數(shù)量. 瘋了!
下載: Lightbox v2.04
package com.founder.web.ext;
import Java.util.Date;
import Java.util.HashMap;
import Java.util.Map;
import org.jmesa.core.filter.DateFilterMatcher;
import org.jmesa.core.filter.FilterMatcher;
import org.jmesa.core.filter.FilterMatcherMap;
import org.jmesa.core.filter.MatcherKey;
public class DateFilterMatcherMap implements FilterMatcherMap {
public Map<MatcherKey, FilterMatcher> getFilterMatchers() {
Map<MatcherKey, FilterMatcher> filterMatcherMap = new HashMap<MatcherKey, FilterMatcher>();
filterMatcherMap.put(new MatcherKey(Date.class, "born"), new DateFilterMatcher("MM/dd/yyyy"));
return filterMatcherMap;
}
}
現(xiàn)在需要修改tableFacade標(biāo)簽為
<jmesa:tableFacade
id="tag"
filterMatcherMap="com.founder.web.ext.DateFilterMatcherMap"
new Ajax.Updater(container, url, options);
// make a HTTP request to the specified URL and update the 'container' element.
Note: to only update a div on success, you may optionally substitute a property list for a simply element id (ie {success:’div_name’} instead of ‘div_name’)
Option | Default value | Description |
asynchronous | true | Type of request |
evalScripts | false | When set as “true”, scripts in requested url are evaluated |
method | ‘post’ | Lets you decide whether to use Get or Post for the request to the server |
contentType | ‘application/x-www-form-urlencoded’ | Allows you to set the content-type sent to the server |
encoding | ‘UTF-8’ | Allows you to determine the encoding type information given to the server |
parameters | ’’ | Allows you to attach parameters to your AJAX request. Most common: parameters:Form.serialize(this) |
postBody | ’’ | Specify data to post. Something like: postBody:’thisvar=true&thatvar=Howdy’ How does this differ from parameters? |
username | ’’ | |
password | ’’ | |
requestHeaders | ’’ | Allows you to override the headers, see the Prototype AJAX options for details |
onComplete | ’’ | Function to call on completion of request |
onSuccess | ’’ | Function to call on successful completion of request |
onFailure | ’’ | Function to call on failed request |
onException | ’’ | Function to call on failed request (e.g. attempted cross-site request) |
on + Status Code | ’’ | on404 etc. raise an event when given status code is encountered. |
insertion | None | Instead of inserting the response in the existing content (possibly overwriting it) you can pass a valid Insertion object, such as Insertion.Top, Insertion.Bottom, Insertion.Before or Insertion.After. |
Hint: If you have set evalScripts:true the script you call (the url parameter) must return a header of ‘Content-Type: text/javascript’ else the browser will not execute it.
Struts2提供了一種可插拔方式來(lái)管理插件,安裝Struts2的JSON插件與安裝普通插件并沒(méi)有太大的區(qū)別,一樣只需要將Struts2插件的JAR文件復(fù)制到Web應(yīng)用的WEB-INF/lib路徑下即可。
安裝JSON插件按如下步驟進(jìn)行:
(1)登陸http://code.google.com/p/jsonplugin/downloads/list站點(diǎn),下載Struts2的JSON插件的最新版本,當(dāng)前最新版本是0.7,我們可以下載該版本的JSON插件。
(2)將下載到的jsonplugin-0.7.jar文件復(fù)制到Web應(yīng)用的WEB-INF路徑下,即可完成JSON插件的安裝。
實(shí)現(xiàn)Actio邏輯
假設(shè)wo,en輸入頁(yè)面中包含了三個(gè)表單域,這三個(gè)表單域?qū)τ谌齻€(gè)請(qǐng)求參數(shù),因此應(yīng)該使用Action來(lái)封裝這三個(gè)請(qǐng)求參數(shù)。三個(gè)表單域的name分別為field1、field2和field3。
處理該請(qǐng)求的Action類代碼如下:
public class JSONExample { //封裝請(qǐng)求參數(shù)的三個(gè)屬性 private String field1; private transient String field2; private String field3; //封裝處理結(jié)果的屬性 private int[] ints = {10, 20}; private Map map = new HashMap(); private String customName = "custom"; //三個(gè)請(qǐng)求參數(shù)對(duì)應(yīng)的setter和getter方法 public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } //此處省略了field1和field2兩個(gè)字段的setter和getter方法 ... //封裝處理結(jié)果的屬性的setter和getter方法 public int[] getInts() { return ints; } public void setInts(int[] ints) { this.ints = ints; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } //使用注釋語(yǔ)法來(lái)改變?cè)搶傩孕蛄谢蟮膶傩悦? @JSON(name="newName") public String getCustomName() { return this.customName; } public String execute() { map.put("name", "yeeku"); return Action.SUCCESS; } } |
serialize:設(shè)置是否序列化該屬性
deserialize:設(shè)置是否反序列化該屬性。
format:設(shè)置用于格式化輸出、解析日期表單域的格式。例如"yyyy-MM-dd'T'HH:mm:ss"。
配置該Action與配置普通Action存在小小的區(qū)別,應(yīng)該為該Action配置類型為json的Result。而這個(gè)Result無(wú)需配置任何視圖資源。
配置該Action的struts.xml文件代碼如下:
<?xml version="1.0" encoding="GBK"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.i18n.encoding" value="UTF-8"/> <package name="example" extends="json-default"> <action name="JSONExample" class="lee.JSONExample"> <result type="json"/> </action> </package> </struts> |
這個(gè)模塊能夠與 views 模塊協(xié)作,它提供一個(gè) views 字段,讓評(píng)分結(jié)果可以通過(guò) views 顯示。