The reason you function doesn't work when lol
is defined outside it, is because the DOM isn't loaded yet when the JavaScript is first run.(在函数库外部定义lol
时,您的函数无法使用的原因是,在首次运行JavaScript时尚未加载DOM 。)
Because of that, getElementById
will return null
( see MDN ).(因此, getElementById
将返回null
( 请参见MDN )。)
You've already found the most obvious solution: by calling getElementById
inside the function, the DOM will be loaded and ready by the time the function is called, and the element will be found like you expect it to.(您已经找到了最明显的解决方案:通过在函数内部调用getElementById
,将在调用函数时加载DOM并准备就绪,并且将按您期望的方式找到该元素。)
There are a few other solutions.(还有其他一些解决方案。) One is to wait until the entire document is loaded, like this:(一种是等到整个文档加载完毕,如下所示:)
<script type="text/javascript">
var lolz;
function onload() {
lolz = document.getElementById('lolz');
}
function kk(){
alert(lolz.value);
}
</script>
<body onload="onload();">
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" onclick="kk();"/>
</body>
Note the onload
attribute of the <body>
tag.(注意<body>
标签的onload
属性。) (On a side note: the language
attribute of the <script>
tag is deprecated. Don't use it.)((附带说明:已弃用<script>
标记的language
属性。请勿使用它。))
There is, however, a problem with onload
: it waits until everything (including images, etc.) is loaded.(但是, onload
存在一个问题:它等待直到所有内容 (包括图像等)都被加载。)
The other option is to wait until the DOM is ready (which is usually much earlier than onload
).(另一个选择是等待DOM准备就绪(通常比onload
早得多)。) This can be done with "plain" JavaScript, but it's much easier to use a DOM library like jQuery .(可以使用“普通” JavaScript来完成,但是使用jQuery之类的DOM库要容易得多。)
For example:(例如:)
<script type="text/javascript">
$(document).ready(function() {
var lolz = $('#lolz');
var kk = $('#kk');
kk.click(function() {
alert(lolz.val());
});
});
</script>
<body>
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" id="kk" />
</body>
jQuery's .ready() takes a function as an argument.(jQuery的.ready()将函数作为参数。) The function will be run as soon as the DOM is ready.(该功能将在DOM准备就绪后立即运行。) This second example also uses .click() to bind kk's onclick
handler, instead of doing that inline in the HTML.(第二个示例还使用.click()绑定kk的onclick
处理程序,而不是在HTML中进行内联。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…