Simple Javascript question
When I click on the button, the first time, everything works fine, but the second time, nothing happens. Why is that?
<form name="alert"><input type="text" name="hour"><input type="text" name="min"><input type="button" value="ok" onclick="budilnik(this.form)">
<script type="text/javascript">
function budilnik(form)
{
budilnik=1;
min=form.min.value;
hour=form.hour.value;
alert (min+' '+hour+' '+budilnik);
}
</script>
Learn to use Firebug. It'll help you immensely in the future.
budilnik=1;
This may sound crazy, but this is redefining the function budilnik to an integer, which breaks your form's onlick. If you preface this statement with keyword var
, you will shadow the function but not overwrite it. When you do not specify the var
keyword, variables are assumed to be global scope, which can cause issues (like this).
I used firebug to see that on the second click, "budilnik is not defined." If you had used this tool, you could have probably debugged this issue yourself.
The variable budilnik
is shadowing the function budilnik
. Change the name of the variable, and your function should work right every time.
In more detail:
First, JavaScript sees budilink
defined as a function. When budilnik
is executed, the value of budilnik
is overwritten with the integer 1. So the next time JavaScript is told to execute budilink
, it tries to execute 1, instead of the function that was there before.
Put the var
keyword before your variable name.
I've tested the following code and it just works:
<form name="alert">
<input type="text" name="hour">
<input type="text" name="min">
<input type="button" value="ok" onclick="budilnik(this.form);">
<script type="text/javascript">
function budilnik(form)
{
var budilnik=1;
var min=form.min.value;
var hour=form.hour.value;
alert (min+' '+hour+' '+budilnik);
}
</script>
链接地址: http://www.djcxy.com/p/96520.html
上一篇: 我应该使用window.variable还是var?
下一篇: 简单的Javascript问题