[英]Unexpected alert being called
I have the following simple script on a page我在页面上有以下简单脚本
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
var nsTest = function ()
{
var test = function ()
{
alert('nsTest.test');
}
var test2 = function ()
{
alert('nsTest.test2');
}
return {
test: test,
test2: test2
}
} ();
function t()
{
alert(nsTest.test());
}
function t2()
{
alert(nsTest.test2());
}
</script>
</head>
<body>
<input type="button" value="test" onclick="t()" />
<input type="button" value="test2" onclick="t2()" />
</body>
</html>
When I click on either of the buttons I see the expected alert on the screent and then a second alert that says 'undefined'.当我单击任一按钮时,我会在屏幕上看到预期的警报,然后是第二个警报,显示“未定义”。
This is happening in IE8 and FF3.这发生在 IE8 和 FF3 中。 Any ideas what is going on?有什么想法吗?
Thanks,谢谢,
David大卫
Your saying alert twice.你这句话提醒了两次。 You do not need to say你不需要说
alert(nsTest.test2());警报(nsTest.test2());
you just need to call nsTest.test2();你只需要调用 nsTest.test2();
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
var nsTest = function ()
{
var test = function ()
{
alert('nsTest.test');
}
var test2 = function ()
{
alert('nsTest.test2');
}
return {
test: test,
test2: test2
}
}();
function t()
{
nsTest.test();
}
function t2()
{
nsTest.test2();
}
</script>
</head>
<body>
<input type="button" value="test" onclick="t()" />
<input type="button" value="test2" onclick="t2()" />
</body>
</html>
Actually you do not even need a function t1 and t2 you can just have your onclick reference nsTest.test2() directly as shown here http://jsbin.com/ageva5/2/edit实际上你甚至不需要 function t1 和 t2 你可以直接让你的 onclick 参考 nsTest.test2() 如下所示Z80791B3AE7002CB88C246876D9FAAbin.com/age
You call t()
which calls nsTest.test()
…你调用t()
调用nsTest.test()
...
nsTest.test()
alerts the string 'nsTest.test'
and then has no return value so returns undefined
. nsTest.test()
警告字符串'nsTest.test'
然后没有返回值,因此返回undefined
。
… t()
then receives the return value and alerts it. … t()
然后接收返回值并警告它。
First the alerts in nsTest are run then the alerts in t() and t2() are run.首先运行 nsTest 中的警报,然后运行 t() 和 t2() 中的警报。 These alerts alert the return value of nsTest.*.这些警报提醒 nsTest.* 的返回值。 These value are undefined.这些值是未定义的。 Remove these alerts to only get the first alert.删除这些警报以仅获取第一个警报。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.