javascript 中如何为多个元素绑定事件,并且该事件的处理函数是已存在的函数?
如下:
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>复选框的全选与全不选</title>
<meta charset="UTF-8" />
<script type="text/javascript">
window.onload = function() {
var arrItem = document.getElementsByName("item");
if (!arrItem) {
return;
}
for (var i = 0; i < arrItem.length; i++) {
var theItem = arrItem[i];
theItem.onclick = function(theItem) // 这个地方我应该怎么写,才能将下面已经存在的函数添加到onclick 事件上
}
}
// 全选或者全不选
function checkSelected(theCheckbox) {
var arrItem = document.getElementsByName("item");
if (!arrItem) {
return;
}
var checkboxAllSelected = document.getElementById("allSelected");
var flag = checkboxAllSelected.getAttribute("checked");
if (!flag) {
flag = "";
}
checkboxAllSelected.setAttribute("checked", flag);
for (var i = 0; i < arrItem.length; i++) {
arrItem[i].setAttribute("checked", flag);
}
}
// 反选
function checkReverse() {
var arrItem = document.getElementsByName("item");
if (!arrItem) {
return;
}
for (var i = 0; i < arrItem.length; i++) {
var flag = arrItem[i].getAttribute("checked");
if (!flag) {
flag = "checked";
} else {
flag = "";
}
arrItem[i].setAttribute("checked", flag);
}
}
// 点击了某一个item 项
function clickItem(theItem) {
alert(theItem.getAttribute("value"));
}
</script>
</head>
<body>
<div>商品列表</div>
<input type="checkbox" name="item" value="3000" />笔记本3000元 <br />
<input type="checkbox" name="item" value="2500" />HTC手机2500元 <br />
<input type="checkbox" name="item" value="8000" />苹果电脑8000元 <br />
<input type="checkbox" name="item" value="1500" />IPAD 1500元 <br />
<input type="checkbox" name="item" value="400" />玩具汽车400<br />
<input type="checkbox" id="allSelected" value="true" onclick="checkSelected(this)" />全选 <br />
<input type="checkbox" id="allReverse" onclick="checkReverse()" />反选 <br />
<input type="button" value="总金额" onclick="getSum()"/><span id="sumId"></span>
</body>
</html>
window.onload = function() {
var arrItem = document.getElementsByName("item");
if (!arrItem) {
return;
}
arrItem.forEach(function(item) {
item.addEventListener('click', function() { clickItem(item); }, false);
})
}