首页 > 解决方案 > How can I make this button have two click events?

问题描述

My program so far will create these nested divs with an image in the inner most div over and over.

I know I can make more than one event happen on the same click but in this case i need them to happen one after the other. so click#1 will result in the nest divs and image#1 but click#2 will result in the nest divs and image#2. click#3 will show image#1 and so on. The even clicks will show the even image, odd shows the odd. i

dk if all of the divs need to be created again or just the image needs to be swapped.

if it helps (havent attmepted so i didnt want to ask yet)....ultimately i need to also create a text box that keeps track of the amount of clicks and uses the current textbox value to change the images.

var i = 0;

function runTogether1() 
  {
    addDiv();
    addDiv2();
    addDiv3();
    addbutterfly();
  }


function addDiv() 
  {
    var div1 = document.createElement('div');
    div1.classList.add('div1');
    document.body.appendChild(div1);
  }

function addDiv2() 
  {
    var div2 = document.createElement('div');
    div2.classList.add('div2');
    document.getElementsByClassName("div1")[i].appendChild(div2);
  }

function addDiv3() 
  {
    var div3 = document.createElement('div');
    div3.classList.add('div3');
    document.getElementsByClassName("div2")[i].appendChild(div3);
  }

function addbutterfly() 
{
var img = document.createElement('img');
img.src = "gorilla.bmp";
document.getElementsByClassName("div3")[i].appendChild(img);
i++;
}
.div1 {
  background-color: red;
  margin: 1em;
  height: 250px;
  width: 250px;
  justify-content: center;
  align-items: center;
}

.div2 {
  background-color: yellow;
  height: 150px;
  width: 150px;
}

.div3 {
  background-color: limegreen;
  height: 75px;
  width: 75px;
}


div {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}
<html>
  <head>
    <meta charset="utf-8">
    <script src ="gorillajs.js" defer></script>
  </head>
  <body>
    <div class="button">
      <button onclick = "runTogether1()"> 
          click to get nested divs
      </button>  
    </div>
 </body>
</html>

标签: javascripthtmlcss

解决方案


创建一个全局布尔变量,每次运行runTogether().时切换为真,运行“奇数”函数,然后将切换设置为假,否则,运行“偶数”函数并将切换设置为真。


推荐阅读