javascript - 使用 jQuery 创建动态按钮
问题描述
我正在尝试使用从文件加载到数组中的文本动态创建按钮。文本加载,数组创建,但没有按钮。我意识到以前有人问过这个问题,但我一定做错了什么。
var database = [];
var total;
document.getElementById('file').onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent) {
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
database[line] = lines[line].trim();
}
total = line;
};
reader.readAsText(file);
};
/*
function mkbuttons() {
for (let i = 0; i < total; i++)
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
$('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
}
});
}
*/
function mkbuttons() {
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
$('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Create Buttons</title>
</head>
<body>
<input type="file" name="file" id="file" accept=".txt">
<br><br>
<button i onclick="mkbuttons()">Make Buttons</button>
</body>
</html>
解决方案
您如何看待这个解决方案?
var database = [];
var total;
document.getElementById('file').onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent) {
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
database[line] = lines[line].trim();
}
total = line;
};
reader.readAsText(file);
};
function mkbuttons() {
for (let i = 0; i < total; i++)
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
var newBtn = $('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
$('#buttons').append(newBtn);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Create Buttons</title>
</head>
<body>
<input type="file" name="file" id="file" accept=".txt">
<br><br>
<button i onclick="mkbuttons()">Make Buttons</button>
<div id="buttons">
</div>
</body>
</html>
推荐阅读
- python - Python - 如何确定数据点是随机的还是聚集的?
- watson-iot - MQTT 客户端与 Watson IoT Platform 断开连接:“主题无效:临时主题与授权规则不匹配”
- c# - C#设置原始类型的泛型属性值
- c++ - Vigenere Encription 与不同的 mod
- c++ - 适用于 C++ 的 Azure 服务总线 SDK
- jquery - 如何使用Jquery删除多个表行
- python - 求解带参数的线性方程
- reactjs - react-slick 与 react-image-zoom 冲突图像缩放不起作用
- python - 版权字符串搜索和替换问题
- node.js - sequelize 连接管理器没有正确关闭连接