<html>
<html class="no-js" lang="en-US"> <!--<![endif]-->
<head data-live-domain="jquery.com">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div>
青菜豆腐
<input type="checkbox" value="1" name="dishes">
</div>
<div>
酸辣土豆丝
<input type="checkbox" value="2" name="dishes">
</div>
<div>
红烧鲫鱼
<input type="checkbox" value="3" name="dishes">
</div>
<div>
辣子鸡
<input type="checkbox" value="4" name="dishes">
</div>
<script>
$('input[name="dishes"]').bind('click',function(){
var ids = $(':checkbox:checked').map(function() {
return this.value;
}).get().join();
$('#dishes').val(ids); // 将选中的dishes保存到表单
alert(ids);
})
</script>
</body>
</html>
map()函数一直都是我认为比较实用的函数之一,为什么这么说呢?
先来考虑一下,你是否碰到过以下场景:需要遍历一组对象取出每个对象的某个属性(比如id)并且用分隔符隔开
我想你一定有碰到过吧!因为我已经碰到过很多次了,这就是map()函数的一个典型的适用场景
不仅在前台,后台也是(所以后面我在java中也简单实现了这么一个方法),下面就看看吧