JavaScript OnChange 侦听器在 HTML 标记中的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12185266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:31:22  来源:igfitidea点击:

JavaScript OnChange Listener position in HTML markup

javascripthtml

提问by Cookiimonstar

I am having problems getting the OnChnage Listener to work, if i position the script after the </form>tag the listener works fine but if i place the script within the <head>tags it fails to work.

我在让 OnChnage 侦听器工作时遇到问题,如果我将脚本放在</form>标签之后,侦听器工作正常,但如果我将脚本放在<head>标签内,它就无法工作。

On my site i can only have the script within the <head>tags is there anything I can do to make the script runn within the <head>tags?

在我的网站上,我只能在<head>标签内放置脚本,我可以做些什么来使脚本在<head>标签内运行?

in this configuration the script does not work

在此配置中,脚本不起作用

<head>
<script type="text/javascript">
if(window.addEventListener) {
    document.getElementById('address').addEventListener('change', loadXMLDoc, false);
} else if (window.attachEvent){
    document.getElementById('address').attachEvent("onchange", loadXMLDoc);
}

function loadXMLDoc(){
   alert('worked');
}
</script>
</head>

<body>
<form>

<input id="address" name="address" type="text"/>
<input id="test" name="test" type="text"/>

 </form>

回答by Teemu

Put it this way:

这么说吧:

<head>
<script type="text/javascript">
window.onload= function () {
    if(window.addEventListener) {
        document.getElementById('address').addEventListener('change', loadXMLDoc, false);
    } else if (window.attachEvent){
        document.getElementById('address').attachEvent("onchange", loadXMLDoc);
    }

    function loadXMLDoc(){
       alert('worked');
    }
}
</script>
</head>

回答by Ethan Brown

Put your code in the window.onloadfunction:

将您的代码放在window.onload函数中:

<head>
<script>
    window.onload = function() {
        if(window.addEventListener) {
            document.getElementById('address').addEventListener('change', loadXMLDoc, false);
        } else if (window.attachEvent){
            document.getElementById('address').attachEvent("onchange", loadXMLDoc);
        }

        function loadXMLDoc(){
            alert('worked');
        }
    }
</script>
<body>
    ...
</body>

回答by Polyov

When you place the script in the <head>, the elements you are getting with document.getElementByIddo not exist yet. Wait for the window to load before adding the event listener.

当您将脚本放在 中时<head>,您使用的元素document.getElementById尚不存在。在添加事件侦听器之前等待窗口加载。

You need to wait for the window to load with a jQuery $(document).readyor by adding a loaded listener to the window:

您需要等待窗口加载 jQuery$(document).ready或向窗口添加加载的侦听器:

window.addEventListener('load',addListener,false);
function addListener() {
    //your code here
}