使用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>

for循环有两个明显的问题:

  1. 只能在函数外使用$(document).ready,且只能使用一次。它不应该在for循环
  2. 你有一个内部循环它也使用相同的索引变量名称i

一旦你修复了这个语法,事情就会更好地工作,或者至少更容易调试。

最新更新