onChange()不能在服务器上工作但在jsfiddle上工作正常吗?

时间:2014-05-06 17:45:26

标签: javascript html dependencies onchange jsfiddle

比较

上的代码

的jsfiddle

HTML

<select name="client_select" id="client_select">
<option value="Name not listed">Name not listed</option>
<option value="1">abc company</option>
</select>
<span id="client_add"><input type="text" name ="" value="field1"/></span>

的Javascript

document.getElementById("client_select").onchange = 
function (e) {
if (this.value == 'Name not listed') {
    document.getElementById("client_add").style.display="";
    } else {
        document.getElementById("client_add").style.display="none";    
    }
};

我的网站

<script>
document.getElementById("client_select").onchange = 
function (e) {
    if (this.value == 'Name not listed') {
        document.getElementById("client_add").style.display="";
    } else {
document.getElementById("client_add").style.display="none";    
    }
};
</script>
<select name="client_select" id="client_select">
<option value="Name not listed">Name not listed</option>
    <option value="1">abc company</option>
</select>
<span id="client_add"><input type="text" name ="" value="field1"/></span>

解决方案:

在将元素加载到客户端DOM后运行javascript。

执行以下操作之一:

  • 在html元素之后加载javascript

  • 使用onLoad()来包装脚本

  • 使用jQuery使用$(document).ready(function(){}

2 个答案:

答案 0 :(得分:1)

当您尝试使用该元素时,该元素不可用,因为它尚未在DOM中加载。

在元素

之后移动脚本
<select name="client_select" id="client_select">
    <option value="Name not listed">Name not listed</option>
    <option value="1">abc company</option>
</select>
<span id="client_add"><input type="text" name ="" value="field1"/></span>

<script>
    document.getElementById("client_select").onchange = function(e) {
        if (this.value == 'Name not listed') {
            document.getElementById("client_add").style.display = "";
        } else {
            document.getElementById("client_add").style.display = "none";
        }
    };
</script>

我还鼓励使用addEventListener

答案 1 :(得分:1)

一个简单的解决方案是将脚本包装在window.onload函数中,如:

window.onload = function(){
    // Do things here...
};

或者如果jQuery可用:

$(function(){
    // Do things here...
});