V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
cuthead
V2EX  ›  JavaScript

为什么只有在 function 里才能 alert document.getElementById("text1").value,无法直接 alert document.getElementById("text1").value

  •  
  •   cuthead · 2015-04-03 02:56:41 +08:00 · 2321 次点击
    这是一个创建于 3283 天前的主题,其中的信息可能已经有所发展或是发生改变。
    <html>
    <head>
    <script type="text/javascript">
    function alertValue()
    {
    alert(document.getElementById("text1").value)
    }
    </script>
    </head>
    <body>

    <form>
    <input type="text" id="text1" value="Hello world!" />
    <input type="button" id="button1" onclick="alertValue()"
    value="Show default value" />
    </form>

    </body>
    </html>

    我想这样
    <html>
    <head>
    <script type="text/javascript">
    alert(document.getElementById("text1").value)
    </script>
    </head>
    <body>

    <form>
    <input type="text" id="text1" value="Hello world!" />
    <input type="button" id="button1" onclick="alertValue()"
    value="Show default value" />
    </form>

    </body>
    </html>
    就无法弹出alert,何解?
    tux
        1
    tux  
       2015-04-03 03:37:21 +08:00
    因为alert的时候,要alert出来的东西还没有加载,把alert放在要alert的东西底下就好了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2871 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 14:25 · PVG 22:25 · LAX 07:25 · JFK 10:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.