html / javascript:无法通过按钮将变量传递给函数?

时间:2020-05-10 23:57:10

标签: javascript html

以下功能位于代码顶部的标记中:

function textcolor(color){
  alert("Working");
  switch(color){
  case "red":
    document.body.style.background = "white";
    document.getElementbyId("content").style.color = 'red';
    break;

等 当我尝试使我的任何按钮具有onclick ='textcolor()'时,警报就很好了,但是当我将其更改为onclick ='textcolor(red)'时,它甚至都没有警报。当我按f12键时,控制台显示“ Uncaught ReferenceError:未定义红色”,当我将鼠标悬停在PHPstorm中的代码上时,它显示“ Unresolved variable or type red”。

2 个答案:

答案 0 :(得分:0)

此代码在您单击按钮时使文本变为红色:

<head>
    <script>
        function textcolor(color) {
            alert("Working");
            switch(color) {
                case "red":
                    document.body.style.background = "white";
                    document.getElementById('content').style.color = 'red';
                    break;
            }
        }
    </script>
</head>

<body>
    <div id="content">This is a test</div>
    <button onclick='textcolor("red")'>Click me</button>
</body>

答案 1 :(得分:0)

似乎您试图通过执行redtextcolor变量传递给textcolor(red)函数,因此,如果您真的想传递名为red的变量,则应该在使用之前定义oit,但是如果您想尝试传递简单的红色字符串,则应尝试像'textcolor("red")'

那样传递它