javascript - 单击生成数字然后将其传递给另一个函数

标签 javascript jquery web

假设我有一些文本和一个按钮:

<p id="text-box">placeholder text</p>
<button id="text-btn">New Quote Please.</button>

当我单击按钮时,我希望在#text-box 中出现一些新内容。所以我创建了一个数组和一些 jQuery 函数:

var textArr = [word0, word1, word2, word3, word4...];

$(document).ready(function() {
  $( "#text-btn" ).click(function(){
    x = Math.floor(Math.random()*textArr.length); //This line is the problem.
  });
  $("#text-box").html(textArr[x]);
});

想法是当单击按钮时生成一个随机数,然后该数字用于选择 textArr 中的项目以显示在#text-box 中。我相当确定问题出在注释行中。我认为 $("#text-btn") 函数中的 x 值要么根本没有被创建,要么没有被传递到 $("#text-box") 函数中。

感谢您的宝贵时间。

最佳答案

向我们展示控制台尝试 console.log 。和文本框 html 必须在点击事件中。

$(document).ready(function() {
  $( "#text-btn" ).click(function(){
    x = Math.floor(Math.random()*quoteArr.length); //This line is the problem.
     console.log('check', Math.floor(Math.random()*quoteArr.length)) 
   $("#text-box").html(textArr[x]);
  });

});

关于javascript - 单击生成数字然后将其传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33980340/

相关文章:

php - 无法使 PHP 脚本运行,它显示为空白页

audio - 您会为服务器端合成器推荐什么设置?

javascript - Angular.js 和 Node.js 获得 GET 而不是 POST

javascript - jquery ui 中的奇怪偏移可拖动

javascript - Android Phonegap 滚动条非常不稳定

javascript - 通过查询仅删除一个 div

javascript - 如何居中一个绝对位置的div?

jquery - 为什么当我尝试将它们放入彼此时,我所有的 JQuery 拖放对象都消失了?

javascript - 当鼠标朝向或位于文档的顶部中心时运行 jQuery

javascript - 发送电子邮件,而不是从我的服务器