[英]jquery - using it on an input field - can't get variable out of function so I can use it
The first time I try to use my jQuery lessons on a real web page, I find that the variable guess
(inside the scope of this inner function) disappears as soon as the function completes. 第一次尝试在真实的网页上使用jQuery课程时,我发现该函数完成后变量guess
(在此内部函数的范围内)消失。
This is normal javascript behavior, I suppose, but how does one usually grab hold of the variable so one can use it in other functions? 我想这是正常的javascript行为,但是通常如何抓住变量,以便可以在其他函数中使用它呢? My lessons never covered that. 我的课程从未涵盖过。
I assumed that once guess
was routed into the innerHTML of #display
, it would stick. 我以为一旦guess
被路由到#display
的innerHTML中,它就会坚持下去。 But it's even disappearing from there. 但是它甚至从那里消失了。
? ?
<!DOCTYPE html>
<html>
<HEAD>
<title>Game of the Century</title>
<meta charset="UTF-8">
<LINK href="reset.css" rel="stylesheet" type="text/css">
<LINK href="main.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="application.js"></script>
</HEAD>
<body>
<form>
<input type='text' name = "input" id = "input"><br>
<input type='submit' id="submit">
</form>
<p id = "display"></p>
<div>
<img src="http://img707.imageshack.us/img707/2403/rj1a.jpg" alt = "ad">
</div>
</body>
</html>
... ...
$(document).ready(function () {
$('#submit').click( function() {
var guess = $('#input').val();
$("#display").html(guess);
});
});
This is absolutely normal and it is not related to jQuery. 这绝对是正常的,与jQuery无关。 Your guess
variable is defined in a closure, anonymous function. 您的guess
变量是在闭包匿名函数中定义的。 So, it lives there and it is not accessible outside of that scope. 因此,它存在于此,并且在该范围之外无法访问。 If you want to use guess
outside the click handler, just define it outside. 如果要在点击处理程序之外使用guess
,只需在外部定义它即可。 For example: 例如:
$(document).ready(function () {
var guess;
$('#submit').click( function() {
guess = $('#input').val();
$("#display").html(guess);
});
var anotherMethod = function() {
alert(guess); // <--- it works
}
});
Also, you don't need to use document.getElementById
if you already include jQuery. 另外,如果您已经包含jQuery,则无需使用document.getElementById
。
Edit: I just saw the html. 编辑:我刚刚看到的html。 There is another side effect of the code. 该代码还有另一个副作用。 Your form is actually submitting when you click the button. 当您单击按钮时,您的表单实际上正在提交。 Try changing the type="submit"
to "type="button"
or some other way to prevent the form submitting. 尝试将type="submit"
更改为"type="button"
或其他防止表单提交的方法。
Just here my solution with perhaps a better split of read/write tasks 就在这里我的解决方案可能具有更好的读写任务分离
$(document).ready(function () {
getMyHtml = function() {
return $('#input').val();
}
setMyHtml = function () {
var s = getMyHtml();
$("#display").html(s);
}
$('#submit').click(setMyHtml);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.