简体   繁体   中英

html/javascript: can't pass variable to function from button?

the following function is in a tag at the top of my code:

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

etc when I try to make any of my buttons have onclick='textcolor()' it does the alert just fine, but when I change that to onclick='textcolor(red)' it doesn't even do the alert. when I hit f12 the console says "Uncaught ReferenceError: red is not defined", and when I mouse over the code in PHPstorm it says "Unresolved variable or type red".

This code makes the text red when you click the button:

<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>

It seems that you are trying to pass a red variable to the textcolor function by doing textcolor(red) so if you really want to pass a variable called red you should define oit before using it, but if you want to try to pass a simple red string you should try passing it like 'textcolor("red")'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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