此代码在第一次单击表节点时添加了我想要的所有内容(添加了图像等)。但是,当单击第二个节点时,选项会再次出现,但会出现两次,依此类推。有没有办法让我只将元素附加一次。我创造了一个问题的小提琴。它适用于Chrome,但不适用于JSFiddle本身。也许我做错了什么。 http://jsfiddle.net/Inkers/NyxCu谢谢。
<html>
<head>
<meta name = "viewport" content="width=device-width, height= device-height, initial-scale=1.0, maximum-scale=1.0"/>
<meta charset=UTF-8"/>
<title>Whatever it is going to be</title>
<script type="text/javascript" charset="utf-8" src="fiddle.js"></script>
</head>
<body>
<h3>Create a new table</h3>
<div id="holdTable">
<form id="chartInput">
<label for="taskname">Task</label>
<input id="taskname" type="text" placeholder="Blah blah"><br>
<label for="days">How many days</label>
<input id="days" name="days" type="number" min="1" max="7"><br>
<label for="times">How many times a day</label>
<input id="times" name="times" type="number" min="1" max="4"> <br>
<input id="createChart" type="button" value="Make the table" onClick="makeChart();"> <br>
</form>
</div>
</body>
</html>
var makeChart = function () {
var table = document.createElement('table'),
taskName = document.getElementById('taskname').value,
header = document.createElement('th'),
numDays = document.getElementById('days').value, //columns
howOften = document.getElementById('times').value, //rows
row,
r,
col,
c;
header.innerHTML = taskName;
table.appendChild(header);
header.innerHTML = taskName;
table.appendChild(header);
function addImage(col) {
var img = new Image();
img.src = "http://cdn.sstatic.net/stackoverflow/img/tag-adobe.png";
col.appendChild(img);
img.onclick = function () {
var myImages = new Array();
myImages[0] = "http://www.olsug.org/wiki/images/9/95/Tux-small.png";
myImages[1] = "http://a2.twimg.com/profile_images/1139237954/just-logo_normal.png";
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
var my_div = document.createElement("div");
my_div.id = "showPics";
document.body.appendChild(my_div);
var newList = document.createElement("ul");
newList.appendChild(allImages);
my_div = document.getElementById("showPics");
my_div.appendChild(newList);
my_div.style.display = 'block';
allImages.onclick = function (e) {
img.src = e.target.src;
my_div.style.display = 'none';
};
}
};
};
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
}
}
document.getElementById('holdTable').appendChild(table);
};