简体   繁体   English

为什么我的JavaScript函数没有运行?

[英]Why aren't my javascript functions running?

I have several functions on my web page that aren't working, here is one - 我的网页上有几个无法使用的功能,这是一个-

    <p> Change background color</p>
    <input name="bg" value="cyan" id="cyan" type="radio" onclick="changebgcolor(this);">"Cyan"
    <input name="bg" value="magenta" id="magenta" type="radio" onclick="changebgcolor(this);">"Magenta"
    <input name="bg" value="lightsalmon" id="lightsalmon" type="radio" onclick="changebgcolor(this);">"Light Salmon"

        function changebgcolor(element){
            document.body.style.backgroundColor = element.value;
        };

Console is telling me my elements are not defined? 控制台告诉我未定义元素?

The other one is a similar function intended to change text color, the rest are form validations. 另一个是旨在更改文本颜色的类似功能,其余功能是表单验证。 and here is the web page I am working on - http://www.acsu.buffalo.edu/~mariaroo/validation.html 这是我正在处理的网页-http: //www.acsu.buffalo.edu/~mariaroo/validation.html

An else statement is not followed by a condition. else语句后没有条件。 You need to change your last else to an else if or remove the condition altogether: 您需要将最后一个else更改为else if或完全删除条件:

// if you plan on adding more color options go this route
else if (color == "lightsalmon"){ 
    document.body.style.backgroundColor = "lightsalmon"
}

// if you're not going to add any more color options this will work as well
else { 
    document.body.style.backgroundColor = "lightsalmon"
}

EDIT 编辑

It looks like you've updated your code and the new issue is that when your HTML is parsed the changebgcolor and changetextcolor functions don't exist yet (they are at the bottom of your page). 看来您已经更新了代码,并且出现了新问题,当解析HTML时, changebgcolorchangetextcolor函数尚不存在(它们位于页面底部)。 To fix this move them up into the <head> portion of your document so they are already initialized before your radio buttons and their onclick event handler is registered. 要解决此问题,请将它们移至文档的<head>部分,以便注册单选按钮和其onclick事件处理程序之前已对其进行初始化。 See my example below: 请参阅下面的示例:

<head>

... // you have meta, title and styling here

  <script>
    function changebgcolor(element){
        document.body.style.backgroundColor = element.value;
    };

    function changetextcolor(element){
        document.body.style.color = element.value;
    };
  </script>
</head>

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

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