首页 > 解决方案 > 使用 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>

标签: javascriptjquerybutton

解决方案


您如何看待这个解决方案?

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>


推荐阅读