我正在尝试使用Electron和一个名为SQlite的数据库来构建应用程序。我想从多个表创建标题和字幕列表。它需要看起来像这样:
**Titlename 1**
- Subname 1
- Subname 2
- Subname 3
**Titlename 2**
- Subname 4
- Subname 5
- Subname 6
这是我的代码:
db.serialize(() => {
var rows = document.getElementById("database");
db.each("SELECT DISTINCT titlename, Subname FROM sqlitedatabase ORDER BY Titleorder", function(err,row) {
// The results from the database (the titlename) are put into <p id="chaptertitle">
var item = document.createElement("p");
item.setAttribute("id", "chaptertitle");
item.textContent = row.chapname;
// The results of the subchapter column go into a second variable:
var item2 = document.createElement("p");
item2.setAttribute("id", "subchaptertitle");
item2.textContent = row.Subchapter;
// Then both <p>-elements are put into the <div id='database'>
rows.appendChild(item);
rows.appendChild(item2);
});
});
// and we close the database
db.close();
结果与我的想法不完全相同
<div id="database">
<p id="chaptertitle">Titlename 1</p>
<p id="subchaptertitle">Subname 1</p>
<p id="chaptertitle">Titlename 1</p>
<p id="subchaptertitle">Subname 2</p>
<p id="chaptertitle">Titlename 1</p>
<p id="subchaptertitle">Subname 3</p>
<p id="chaptertitle">Titlename 2</p>
<p id="subchaptertitle">Subname 4</p>
<p id="chaptertitle">Titlename 2 </p>
<p id="subchaptertitle">Subname 5</p>
<p id="chaptertitle">Titlename 2</p>
<p id="subchaptertitle">Subname 6</p>
</div>
它应该像这样:
<div id="database">
<p id="chaptertitle">Titlename 1</p>
<p id="subchaptertitle">Subname 1</p>
<p id="subchaptertitle">Subname 2</p>
<p id="subchaptertitle">Subname 3</p>
<p id="chaptertitle">Titlename 2</p>
<p id="subchaptertitle">Subname 4</p>
<p id="subchaptertitle">Subname 5</p>
<p id="subchaptertitle">Subname 6</p>
</div>
我该如何解决?我想我需要使用某种循环,但是我不知道该怎么做。诸如“ foreach章节标题选择相应的字幕”之类的东西。你能帮我吗?
答案 0 :(得分:0)
只需回答我自己的问题即可:
我将子节点添加到了错误的父节点。这有效:
// The results of the subchapter column go into a second variable
var item2 = document.createElement("p");
item2.setAttribute("id", "subchaptertitle");
item2.textContent = row.Subchapter;
// add the subchapter as a childnode to the parentnode (var item)
rows.appendChild(item);
item.appendChild(item2);
将项目追加到<div id="database">
(可变行),将项目2追加到<p id="chaptertitle">
(可变项)。