1 HTML 代碼: 2 <p><b>Values: </b></p> 3 <form> 4 <input type="text" name="name" value="John"/> 5 <input type="text" name="password" value="password"/> 6 <input type="text" name="url" value="http://ejohn.org/"/> 7 </form>
1 jQuery 代碼: 2 $("input").map(function(){ 3 return $(this).val(); 4 }).get().join(", ") ;
結果:
John, password, http://ejohn.org/
// 注意return關鍵字不可少
map先遍歷,每一項都返回一個val()值,然后map會將這些值自動去替換$("input")集合的每一項值,所以這個時候還是個類數組(因為還是$(" input")的殼子),不是個真正的數組。於是后面加個get()操作就變成真正的數組了,於是可以用join()這樣專屬於數組的方法。