用按钮存储生成的句子

时间:2016-07-06 03:16:37

标签: javascript html arrays

我有一个小的webapp试图找出工作原理...... 现在,"创建新的启动"按钮生成一个字符串,其中包含来自数组的一个输入" startupX'还有一个来自'startupY'。我试图找出如何获得最喜欢的创业公司"按钮存储生成的整个字符串,然后最终能够打印出所有被"打印收藏夹"按钮。我可以以某种方式将字符串保存为str.split()的数组吗?



var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];

function chooseStartup() {
var x = startupX[Math.floor(Math.random()*startupX.length)];
var y = startupY[Math.floor(Math.random()*startupY.length)];

document.getElementById('startupX').innerHTML = x;
document.getElementById('startupY').innerHTML = y; 
};

<body>

   <h1 id="xForY"></h1>
<h1 id="sentence">A startup that is 
    <span id="startupX"></span>, but for 
    <span id="startupY"></span>
</h1>
  <div id="inputs">
    <button onclick="chooseStartup()" id="create">Create New Startup</button>   
    <button id="save">Favorite Startup</button>
    <button id="print">Print Favorites</button>
  </div>

  <h2 id="favorites">

  </h2>


  <script src='http://code.jquery.com/jquery-latest.min.js'></script>
  <script src='js/madlib-console.js'></script>

</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

请在下面找到一个工作示例。希望这会有所帮助。

var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];
var x = y = '',
  arr = [];

function chooseStartup() {
  x = startupX[Math.floor(Math.random() * startupX.length)];
  y = startupY[Math.floor(Math.random() * startupY.length)];

  document.getElementById('startupX').innerHTML = x;
  document.getElementById('startupY').innerHTML = y;
};

$('#save').click(function() {
  if (x != '' && y != '') {
    arr.push('A startup that is ' + x + ' but for ' + y);
  }
});

$('#print').click(function() {
  $('#favorites').html(arr.toString().split(',').join('<br />'));
});
<body>

  <h1 id="xForY"></h1>
  <h1 id="sentence">A startup that is 
    <span id="startupX"></span>, but for 
    <span id="startupY"></span>
</h1>
  <div id="inputs">
    <button onclick="chooseStartup()" id="create">Create New Startup</button>
    <button id="save">Favorite Startup</button>
    <button id="print">Print Favorites</button>
  </div>

  <h2 id="favorites">

  </h2>


  <script src='http://code.jquery.com/jquery-latest.min.js'></script>
  <script src='js/madlib-console.js'></script>

</body>