我正在使用Electron开发一个应用程序,我想制作不同的页面。我创建了一个索引.html,另一个索引:seeds.html。(我将添加更多,这个仅用于测试(我所做的是通过 jQuery .load()
在 index.html 中带有"main"类的div 中加载所选页面的内容(例如 addseed.html(。现在的问题是在我加载addseed
之后,该表没有显示较旧的查询。我测试过,它可以正确读取文件,但主要问题是将它们附加到动态创建的表中。但是,在我添加新项目后,它会正确显示,但旧项目不会。
(有"联系人"而不是"种子",因为我正在学习教程,代码仅用于测试:D
function addEntry(seed, price, image) {
if(seed && price && image) {
sno++
let updateString = '<tr> <td>' + sno + '</td> <td>'+ seed +'</td> <td>' + price +'</td> <td> <img width="200px" height="200px" src="' + image + '"> </td> </tr>'
$('#contact-table').append(updateString)
}
}
function loadAndDisplayContacts() {
$("#status").text("function worksn")
//Check if file exists
if(fs.existsSync('contacts.txt')) {
let data = fs.readFileSync('contacts.txt', 'utf8').split('n')
data.forEach((contact, index) => {
let [ seed, price, image ] = contact.split(',')
addEntry(seed, price, image)
})
} else {
console.log("File Doesn't Exist. Creating new file.")
fs.writeFile('contacts.txt', '', (err) => {
if(err)
console.log(err)
})
}
}
$(document).on('click', '#addseed', () => {
$(".main").load("addseed.html")
loadAndDisplayContacts()
})
这是"addseed.html"的html:
<div class="container main">
<div class="form-group">
<label for="Seed">Seed</label>
<input type="text" Seed="Seed" value="" id="Seed" placeholder="Seed" class="form-control" required>
</div>
<div class="form-group">
<label for="Price">Price</label>
<input type="Price" Seed="Price" value="" id="Price"
placeholder="Price" class="form-control" required>
</div>
<div class="form-group">
<label for="Image">Image</label>
<input type="Image" Seed="Image" value="" id="Image"
placeholder="Image" class="form-control" required>
</div>
<button id="openFile" onclick="openFile();">Open</button>
<p>this is filepath: <span id="filee"></span></p>
<div class="form-group">
<button class="btn btn-primary" id="add">Add to list!</button>
</div>
<div id="contact-list">
<table class="table-striped" id="contact-table">
<tr>
<th class="col-xs-2">S. No.</th>
<th class="col-xs-4">Seed</th>
<th class="col-xs-6">Price</th>
<th class="col-xs-8">Image</th>
</tr>
</table>
</div>
</div>
在index.html
中,我有:
<button id="addseed">Add</button>
<div class="main"></div> <!--the content should be added here as a child of main-->
<p id="status"></p>
您不是在等待异步 AJAX 完成。您需要将依赖于更新的 DOM 的函数调用为回调函数。
$(document).on('click', '#addseed', () => {
$(".main").load("addseed.html", loadAndDisplayContacts)
})
而在addseed.html
中,将class="container main"
改为仅class="container"
。您将文件加载到index.html
中的main
DIV 中,它不会替换 DIV。因此,您将使用该类创建两个 DIV,下一次单击会将文件加载到这两个 DIV 中。