简体   繁体   English

Javascript:onchange无法正常工作

[英]Javascript:onchange not working

I want to change my HTML page based on some input. 我想根据一些输入更改我的HTML页面。 So I tried using javascript event handlers to achieve this. 所以我尝试使用javascript事件处理程序来实现这一点。 But they doesn't seem to work at all. 但它们似乎根本不起作用。 Here's my code: 这是我的代码:

var nam = document.getElementById('FNAME');
nam.onchange=test();
function test(){
alert("test");
}

This only works for one time when the page loads. 这仅在页面加载时有效一次。

I've included this external javascript file in my HTML code just before closing the body tag. 在关闭body标签之前,我已将此外部javascript文件包含在我的HTML代码中。

This only works for one time when the page loads. 这仅在页面加载时有效一次。

No. It doesn't work even when the page loads for the first time. 不会。即使第一次加载页面也不起作用。 It's just that you're getting an alert due to the invocation of test . 这只是因为调用test而得到警报。

onchange expects a function reference, which it will invoke when it's associative event is triggered. onchange需要一个函数引用,它会在触发关联事件时调用它。 So you should be doing 所以你应该这样做

nam.onchange = test; // don't call it, just pass the reference.

There are two more easy ways (except function reference): 还有两种简单的方法(功能参考除外):

nam.onchange = function(){
    alert("test");
}

or 要么

nam.onchange = function(){
    test();
}

up to you 由你决定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM