简体   繁体   中英

Change variable value on button click

very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a variable = "yes" . The variable value will change on a button click. I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.

Was hoping someone would be kind enough to help.

I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)

HTML:

<button id="butterbutton" onclick="imageAdd('yes'); ">
  <img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>                
</button>

JS:

var beast
function imageAdd(choice) {
  beast = choice;
}

if (beast = "yes" ) {
  function imagemap () {
    document.getElementById('test1').innerHTML += '<img> an image map goes here';
  }
}

http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010

You have just a couple of problems with your code. The first is this:

if (beast = "yes") {

In this case, you're assigning "yes" to beast , not comparing it. Change it to

if (beast == "yes") {

Next, your code at the bottom ( if (beast == "yes") { ... ) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd . While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.

var beast;
function imageAdd(choice) {
  beast = choice;
  updateUI();
}

function updateUI() {
  if (beast == "yes") {
    document.getElementById('test1').innerHTML += '<img> an image map goes here';
  }
}

You have a function imagemap wrapped in a conditional but you aren't calling that function.

Also for your conditional, beast will always be null since the conditional is called straight away.

Consider the following adjustment

var beast;

function imagemap () {
  document.getElementById('test1').innerHTML += '<img> an image map goes here';
}

function imageAdd(choice) {
  beast = choice;

  if (beast === "yes" ) {
    imagemap();
  }
}

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