这是一些执行您所说的JavaScript:
window.addEventListener("load", function () {
"use strict";
var imgClick = function (elemSelected, elemThis) {
var idIndex;
if ((idIndex = imgSelected.indexOf(elemThis.id)) === -1) {
imgSelected.push(elemThis.id);
elemThis.className = "selected"
} else {
imgSelected.splice(idIndex, 1);
elemThis.className = "unselected";
};
console.log(elemSelected);
}
var imgDiv = document.getElementById("imgDiv");
var imgChildren = imgDiv.children;
var imgElements = [];
var imgSelected = [];
var i;
for (i = 0; i < imgChildren.length; i += 1) {
imgElements.push(imgChildren[i]);
imgChildren[i].addEventListener("click", function () {imgClick(imgSelected, this)});
}
});
以下是相关的 HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script type="text/javascript" src="imageSelect.js"></script>
<style type="text/css">
img.unselected {
border-color: black;
border-width: 1px;
border-style: solid;
}
img.selected {
border-color: red;
border-width: 3px;
border-style: solid;
}
</style>
<body>
<div id="imgDiv">
<img class="unselected" id="img01" src="intrepidWidgets.ico" title="Unselected"/>
<img class="unselected" id="img02" src="300px-Java_logo_svg.png" title="Unselected"/>
</div>
</body>
</html>
这是一个讨论 Array 全局对象的 indexOf 属性的链接。它可能与 IE 9 之前的 Internet Explorer 存在兼容性问题,但他们有代码来解决这个问题:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
这是工作代码的链接。您需要打开控制台查看生成的日志(在 Chrome 中按 F12):
http://www.quirkscode.com/flat/forumPosts/imgSelect/imageSelect.html
MDN also discusses addEventListener (search for that element name). It is the preferred way now of adding event listeners, but has compatibility issues with IE < 9: