實(shí)例
構(gòu)建表單中所有值的列表:
$("p").append( $("input").map(function(){
return $(this).val();
})
.get().join(", ") );
定義和用法
map() 把每個(gè)元素通過函數(shù)傳遞到當(dāng)前匹配集合中,生成包含返回值的新的 jQuery 對(duì)象。
語法
.map(callback(index,domElement))
參數(shù) | 描述 |
---|---|
callback(index,domElement) | 對(duì)當(dāng)前集合中的每個(gè)元素調(diào)用的函數(shù)對(duì)象。 |
詳細(xì)說明
由于返回值是 jQuery 封裝的數(shù)組,使用 get() 來處理返回的對(duì)象以得到基礎(chǔ)的數(shù)組。
.map() 方法對(duì)于獲得或設(shè)置元素集的值特別有用。請(qǐng)思考下面這個(gè)帶有一系列復(fù)選框的表單:
<form method="post" action=""> <fieldset> <div> <label for="two">2</label> <input type="checkbox" value="2" id="two" name="number[]"> </div> <div> <label for="four">4</label> <input type="checkbox" value="4" id="four" name="number[]"> </div> <div> <label for="six">6</label> <input type="checkbox" value="6" id="six" name="number[]"> </div> <div> <label for="eight">8</label> <input type="checkbox" value="8" id="eight" name="number[]"> </div> </fieldset> </form>
我們能夠獲得復(fù)選框 ID 組成的逗號(hào)分隔的列表:
$(':checkbox').map(function() {
return this.id;
})
.get().join(',');
本次調(diào)用的結(jié)果是字符串:"two,four,six,eight"。
在 callback 函數(shù)內(nèi)部,this 引用每次迭代的當(dāng)前 DOM 元素。該函數(shù)可返回單獨(dú)的數(shù)據(jù)項(xiàng),或者是要被插入結(jié)果集中的數(shù)據(jù)項(xiàng)的數(shù)組。如果返回的是數(shù)組,數(shù)組內(nèi)的元素會(huì)被插入集合中。如果函數(shù)返回 null 或 undefined,則不會(huì)插入任何元素。
更多建議: