答案 0 :(得分:0)
我们这里有两个问题,一个是选择,另一个是生成。生成很简单:
通知:此操作既快速又肮脏; innerHtml不应使用,如果您希望看到它更优美,请给我Ping :) https://jsfiddle.net/ynfb3Lh2/9/
<div id="selection">
</div>
<div id="target">
</div>
<pre id="text">
</pre>
<script>
// Prepare our targets
const selectionContainer = document.getElementById("selection");
const targetContainer = document.getElementById("target");
const textContainer = document.getElementById("text");
// rows: How many rows to generate?
// cols: How many cols to generate?
// [_insertCallback]: should we insert callback?
// [_targetContainer]: where should we place created divs?
// [_textContainer]: sWhere should we write our HTML as plain text?
function generateDiv(rows, columns, _insertCallback, _targetContainer, _textContainer) {
// Create our wrapping elements
const table = document.createElement("table");
const tbody = document.createElement("tbody");
for (let r = 0; r < rows; ++r) {
// Each row is created here...
const tr = document.createElement("tr");
for (let c = 0; c < columns; ++c) {
const td = document.createElement("td");
td.text = " "
// if callback is defined, and we have a target - allow us to generate new table on each click
if (_insertCallback && _targetContainer) {
td.onclick = () => generateDiv(r + 1, c + 1, false, _targetContainer, _textContainer)
}
tr.appendChild(td)
}
// ... and added here
tbody.appendChild(tr)
}
table.appendChild(tbody)
if (_targetContainer && !_insertCallback ) {
_targetContainer.innerHTML = '';
_targetContainer.appendChild(table);
}
if (_textContainer && !_insertCallback ) {
_textContainer.innerHTML = table.outerHTML
.replace(/td><\//gi, "td>&nbsp;</")
.replace(/</gi, "<")
.replace(/>/gi, ">\n");
}
return table;
}
selectionContainer.appendChild(generateDiv(10, 10, true, targetContainer, textContainer));
</script>
类似地,通过类似的功能(将行和列信息添加到每个单元格)来创建可选择表。然后,表上的mouseClick事件将读取行和列,并传递给生成代码。