javascript - 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>
解决方案
创建一个全局布尔变量,每次运行runTogether().
时切换为真,运行“奇数”函数,然后将切换设置为假,否则,运行“偶数”函数并将切换设置为真。
推荐阅读
- if-statement - If/Then 语句写入,用于从另一个单元格中提取空白单元格
- python - 使用跨度对象。[斯帕西,蟒蛇]
- powershell - 在 .BAT 程序中获取 Powershell 返回代码
- javascript - 如何禁用 vuejs 路由器链接?
- kubernetes - 有条件的舵钩
- c# - 选择语句:无效的列名,在 C# 中使用 Dapper
- php - 从数组 .. 中查找字符串中的所有匹配项并返回匹配项
- android - 当我在数据库中保存为时间戳的日期临近时,Firestore 是否可以向我的应用发送通知?
- matlab - 缺少 Matlab 共享库导致的错误
- android - java.io.FileNotFoundException: Permission denied - 在颤振中我得到了这个错误