开发者

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()" />
    <开发者_如何学JAVA;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. Any ideas what is going on?

Thanks,

David


Your saying alert twice. You do not need to say

alert(nsTest.test2());

you just need to call 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


You call t() which calls nsTest.test()

nsTest.test() alerts the string 'nsTest.test' and then has no return value so returns undefined.

t() then receives the return value and alerts it.


First the alerts in nsTest are run then the alerts in t() and t2() are run. These alerts alert the return value of nsTest.*. These value are undefined. Remove these alerts to only get the first alert.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜