如何根据数据库内容创建HTML按钮?
How to create HTML button based on database content?
尝试学习处理数据库信息,我的任务是根据数据库查询的内容动态创建按钮。
我的Javascript如下:
var Datastrore = require("nedb");
var db = new Datastrore({ filename: "macros.db" });
db.loadDatabase(function(err) {
db.find({}, function(err, docs) {
console.log(docs); //all docs
});
});
这会在控制台中显示我的数据库信息:
0: {name: "asas", command: "asas", _id: "6L83tJLl7ks0iS0b"}
1: {name: "asas", command: "asas", _id: "9kXMI7DdJBWK0L1W"}
2: {name: "qw", command: "qw", _id: "UmOaMJxYjMNjcEQ0"}
现在我不知道如何使用此信息在我的 html 页面上动态创建按钮。
for (var doc in docs) {
var element = document.createElement("button");
//Assign different attributes to the element.
element.setAttribute("name", doc.name);
element.innerHTML = doc.name
element.setAttribute("id", doc._id);
//element.setAttribute("onclick", ); If you wish to add click event
//Append the element in page (in span).
document.body.appendChild(element);
}
首先,您需要在每个条目中循环:
for(var data in docs){
var btn = document.createElement('button') //creates a new button element
var t = document.createTextNode(data.name) //assuming button's name = 'name'
btn.appendChild(t)
btn.id = data._id
btn.onclick = data.command //assuming 'command' is a defined function
document.body.appendChild(btn)
}
尝试学习处理数据库信息,我的任务是根据数据库查询的内容动态创建按钮。
我的Javascript如下:
var Datastrore = require("nedb");
var db = new Datastrore({ filename: "macros.db" });
db.loadDatabase(function(err) {
db.find({}, function(err, docs) {
console.log(docs); //all docs
});
});
这会在控制台中显示我的数据库信息:
0: {name: "asas", command: "asas", _id: "6L83tJLl7ks0iS0b"}
1: {name: "asas", command: "asas", _id: "9kXMI7DdJBWK0L1W"}
2: {name: "qw", command: "qw", _id: "UmOaMJxYjMNjcEQ0"}
现在我不知道如何使用此信息在我的 html 页面上动态创建按钮。
for (var doc in docs) {
var element = document.createElement("button");
//Assign different attributes to the element.
element.setAttribute("name", doc.name);
element.innerHTML = doc.name
element.setAttribute("id", doc._id);
//element.setAttribute("onclick", ); If you wish to add click event
//Append the element in page (in span).
document.body.appendChild(element);
}
首先,您需要在每个条目中循环:
for(var data in docs){
var btn = document.createElement('button') //creates a new button element
var t = document.createTextNode(data.name) //assuming button's name = 'name'
btn.appendChild(t)
btn.id = data._id
btn.onclick = data.command //assuming 'command' is a defined function
document.body.appendChild(btn)
}