如何運用 jQuery.map() 方法?
map 方法將 jQuery 物件中的一組元素轉換為 jQuery 陣列中的另一組值,此陣列可能包含或不包含元素。
以下為 jQuery.map() 方法的引數
- 回撥 − 在集合中每個元素上執行的函式。
示例
你可以嘗試執行以下程式碼,瞭解如何使用 jQuery.map() 方法
<html>
<head>
<title>jQuery Map Method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var mappedItems = $("li").map(function (index) {
var replacement = $("<li>").text($(this).text()).get(0);
if (index == 0) {
// make the first item all caps
$(replacement).text($(replacement).text().toUpperCase());
} else if (index == 1 || index == 3) {
// delete the second and fourth items
replacement = null;
} else if (index == 2) {
// make two of the third item and add some text
replacement = [replacement,$("<li>").get(0)];
$(replacement[0]).append("<b> - A</b>");
$(replacement[1]).append("Extra <b> - B</b>");
}
// replacement will be an dom element, null,
// or an array of dom elements
return replacement;
});
$("#results").append(mappedItems);
});
</script>
<style>
body { font-size:16px; }
ul { float:left; margin:0 30px; color:blue; }
#results { color:red; }
</style>
</head>
<body>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
<ul id = "results">
</ul>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP