假设我有一些文本和一个按钮:
<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/