[英]What is the meaning of this code in Javascript
我是Java语言的新手,我很难正确理解此代码的含义。 我想分享我对代码的看法,需要您的指导以正确理解它。
<body>
<form>
<input type="button" value="Click Me!" id="say_hi" />
</form>
<script type="text/javascript" src="js_event_01.js"></script>
</body>
function hi_and_bye() {
window.alert('Hi!');
window.alert('Bye!');
}
var hi_button = document.getElementById("say_hi");
hi_button.onclick = hi_and_bye;
我的理解:ID为“ get_alerts”时,事件“ onclick”调用函数“ hi_and_bye”。 类似地,这可以应用于任何事件,并且我可以为任何元素赋予id属性,并且该id负责制作可访问的相应输入元素。
您的理解是正确的。 您可以给任何DOM元素一个id
,不仅是输入。 然后,使用getElementById
可以检索对此元素的引用。
在此示例中,这就是您正在做的事情:
// Get a reference to a DOM element that has id="say_hi"
var hi_button = document.getElementById("say_hi");
// subscribe to the onclick event handler of the DOM element we retrieved on
// the previous line and attach this handler to the hi_and_bye javascript function
hi_button.onclick = hi_and_bye;
我认为该函数本身不需要更多解释:当该函数执行时,它将仅一次显示2条警报。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.