繁体   English   中英

我怎样才能让这个应用程序使用当前的文本框值,也就是点击次数,改变 div 中的图像?

[英]How can i make this application use the current textbox value, which is the number of clicks, change the image in the div?

我已经创建了这个应用程序,现在当它运行时,文本框值随着我想要的每次点击而增加。

嵌套的 div 也是使用放置在最里面的 div 中的图像创建的。 如何使用文本框中的值使该图像在两个图像之间切换? 因此,如果文本框中的值是 = 奇数,因为我单击按钮 1 次,它会显示 image1.jpg,如果文本框中的值是 = 任何偶数,则显示 image2.jpg

我只需要嵌套的 div 在第一次点击时出现,并且每次点击都会改变图像,使用文本框中的 vlue 来实现这一点。

我打算使用一个布尔值,但它必须使用文本框中的值。 我知道我没有将该 var 设为全局,所以也许这就是我遇到的问题。 idk 是否进入 addbutterfly 函数或与按钮一起使用的函数。 在此应用程序结束时需要大量帮助

 var i = 0; function runTogether1() { addDiv(); addDiv2(); addDiv3(); addbutterfly(); incrementValue(); } 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 = "bfly1.gif"; document.getElementsByClassName("div3")[i].appendChild(img); i++; } function incrementValue() { var value = parseInt(document.getElementById('id1').value, 10); value = isNaN(value) ? 0 : value; value++; document.getElementById('id1').value = value; }
 <html> <head> <meta charset="utf-8"> <script src ="bflyjs.js" defer></script> </head> <body> <div class="button"> <button onclick = "runTogether1()"> click to get nested divs </button> <textarea id ="id1"> </textarea> </div> </body> <style> .div1 { background-color: red; margin: 1em; height: 500px; width: 500px; justify-content: center; align-items: center; } .div2 { background-color: yellow; height: 300px; width: 300px; } .div3 { background-color: limegreen; height: 150px; width: 150px; } div { display: flex; justify-content: center; align-items: center; position: relative; } </style </html>

函数addbutterfly()负责添加图像,因此您可以获取其中textfield的值。

由于您知道当前值,因此可以按照您想要的方式使用它。 在这种情况下,它应该如下所示:

function addbutterfly() {
  var img = document.createElement('img');

  // Get the value of the "textfield"
  const value = parseInt(document.getElementById('id1').value, 10);

  // If the value is even, add "bfly2.gif", otherwhise add "bfly1.gif"
  img.src = value % 2 === 0 ? "bfly2.gif" : "bfly1.gif";

  document.getElementsByClassName("div3")[i].appendChild(img);
  i++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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