jQuery map函数
map方法将jQuery对象中的一组元素转换为jQuery数组中可能包含或不包含元素的另一组值。
您可以尝试运行以下代码来学习如何使用jQuery.map()方法:
<html>
<head>
<title>jQuery Map Method</title>
<script src = "https://cdn.staticfile.org/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) {
//使第一个项目全部大写
$(replacement).text($(replacement).text().toUpperCase());
} else if (index == 1 || index == 3) {
//删除第二和第四项
replacement = null;
} else if (index == 2) {
//在第三项中添加两项,并添加一些文本
replacement = [replacement,$("<li>").get(0)];
$(replacement[0]).append("<b> - A</b>");
$(replacement[1]).append("Extra <b> - B</b>");
}
//替换将是一个dom元素,为null,
//或dom元素数组
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>jQuery的每个功能
该each()方法是针对每个匹配元素运行的函数。
您可以尝试运行以下代码,以了解如何使用jQuery中的每个函数:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){
alert($(this).text())
});
});
});
</script>
</head>
<body>
<button>Value</button>
<ol>
<li>India</li>
<li>US</li>
<li>UK</li>
</ol>
</body>
</html>