在jQuery中调用表单输入并运行函数
Calling form input in jQuery and running function
这是我关于堆栈溢出的第一个问题,我只编码了几个月,我知道我可能只是在这里错过了一些简单的东西。我正在尝试创建一个简单的程序用于学习目的,计算机自动选择1-100之间的数字,然后用户选择数字,如果他们的选择相对于计算机编号是热的还是冷的,都会收到警报。
我正在尝试将用户答案从表单字段传递到 JavaScript 变量中,然后在单击按钮时运行该函数以测试他们的答案。我正在为这两个问题使用 jQuery。
这是应用程序实时:http://keithlamar.github.io/HotOrCold/
这是我的 HTML:
<form>
Your Number <input id="guess" type="number" name="yournumber"><br>
</form>
<p id="pick">Click Here</p>
这是我的JavaScript:
var userNum = $('#guess').val();
var comNum = Math.floor(Math.random()*101);
var difference = function (a,b) {return Math.abs(a - b)};
var askNumber = function(){
if(userNum == comNum){
alert("You got it! You Win!")
}
else if(difference(userNum,comNum) < 5){
alert("Very Hot!");
}
else if(difference(userNum,comNum) < 10){
alert("Hot!");
}
else if(difference(userNum,comNum) < 20){
alert("Warm!");
}
else if(difference(userNum,comNum) > 20){
alert("Very Cold!")
}
else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function(){
$('#pick').click(function(){
askNumber();
});
});
似乎var userNum
没有从输入中获取值。我认为这可能与函数中的函数嵌套有关,但我不完全确定!
感谢您的任何输入!!
您需要读取函数中的值 - 在您的代码中,您在页面加载期间(点击发生之前)读取输入字段
function difference(a, b) {
return Math.abs(a - b)
};
function askNumber() {
//read the user input in the click handler
var userNum = parseInt($('#guess').val(), 10);
var comNum = Math.floor(Math.random() * 101);
//calculate the difference only once then reuse it
var diff = difference(userNum, comNum);
if (diff == 0) {
alert("You got it! You Win!")
} else if (diff < 5) {
alert("Very Hot!");
} else if (diff < 10) {
alert("Hot!");
} else if (diff < 20) {
alert("Warm!");
} else if (diff > 20) {
alert("Very Cold!")
} else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function () {
$('#pick').click(function () {
askNumber();
});
});
演示:小提琴
相关文章:
- jQuery在元素的上下文中运行函数
- Promise函数在.then之后未运行函数化
- 在.append之后运行函数
- 在on.change事件之后运行函数
- 如果文本或值以字符开头,请运行函数
- 如何在节点模块中从命令行运行函数
- 在Fancybox中提交表单时运行函数
- Don'如果字段为空,则不运行函数
- Javascript:如何在页面重新加载后运行函数
- 成功ajax:如果是200状态代码,则运行函数else另一个函数
- 运行函数ifsuccess($.ajax)有200个状态代码
- JavaScript只有在最后一次被调用时才运行函数
- 在异步AJAX调用完成后,通过变量运行函数
- ng中继器打印结果0;当我运行函数时
- 谷歌扩展:如何在弹出窗口中按下按钮时在我的javascript文件中运行函数
- 获取对在 JavaScript 中运行函数的对象的引用
- 运行函数时出错
- 节点.js子进程中的运行函数
- $.getJSON 在返回数据后不会运行函数
- 如果onchange为true,如何运行函数