简体   繁体   中英

How can I solve this problem with Javascript?

I want to call a Javascript function when the user clicks a button, but the function is inside a condition. Here is the HTML:

 <button id="demo" onclick="myFunction">Hello</button>

And here is the Javascript function:

 var x = document.getElementById("demo"); if (x == "Hello") function myFunction { document.getElementById("demo").innerHTML = "Good morning"; }

When I click on the button nothing happens. If I delete the if statement, the function work, but I want it to be into a condition. Can you help me in solving this stupid problem?

You'll need to change your function to something like this

function myFunction (){
   var x = document.getElementById("demo");
   if (x.innerHTML == "Hello"){
      document.getElementById("demo").innerHTML = "Good morning";
   }
}

There are 2 issues here:

  1. You forgot to add the parenthesis to the function
    <button id="demo" onclick="myFunction()">Hello</button>  
  1. Here x is the Button object and not it's inner text. Thus you use innerHTML to get the text and then compare.
function myFunction() {
    var x = document.getElementById("demo").innerHTML;
    if (x == "Hello"){
        document.getElementById("demo").innerHTML = "Good morning";
      }
    }

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