使用eventlistner点击值从函数中循环输出

时间:2019-01-09 21:22:53

标签: javascript

这是我到目前为止所拥有的代码,但是所有代码都会使第一个气球更改和id发生变化,就像单击的每个div id一样,将输出提供给单击的div。不知道我是否可以将其组合为简单函数,还是应该为每个div分别创建1个函数。

document.getElementById("baloon1").addEventListener("click", eggBasket);
document.getElementById("baloon2").addEventListener("click", eggBasket);
document.getElementById("baloon3").addEventListener("click", eggBasket);
function eggBasket(){
    var dispImages = new Array ();
    dispImages[1] = "images/1.png";
    dispImages[2] = "images/2.png";
    dispImages[3] = "images/3.png";
    dispImages[4] = "images/4.png";
    var rnd = Math.floor( Math.random() * dispImages.length );
        if( rnd == 0 ) {
        rnd =1;
        }
            if (document.getElementById("baloon1")){
                document.getElementById("baloon1").innerHTML = "<img src='" + dispImages[rnd] + "'/>";
            }
            else if (document.getElementById("baloon2")){
                document.getElementById("baloon2").innerHTML = "<img src='" + dispImages[rnd] + "'/>";
            }
            else if (document.getElementById("baloon3")){
                document.getElementById("baloon3").innerHTML = "<img src='" + dispImages[rnd] + "'/>";
            }
}

所有这些都在被称为php页面的scripts.js文件中。

更正了函数名称

在这里html

echo'
<div id="baloon1">
    <img src="' . $randomImage . '">
</div>
<div id="baloon2">
    <img src="' . $randomImage2 . '">
</div>
<div id="baloon3">
    <img src="' . $randomImage2 . '"/>
</div>';

4 个答案:

答案 0 :(得分:1)

在这里,我们用相同的方法将每个鸡蛋绑在一起。

document.querySelectorAll('.egg').forEach(egg => {
  egg.addEventListener("click", (event) =>  {
    console.log(`you clicked on ${event.target.id}`);
  });
  
});
<div id="egg1" class="egg"> Egg1 </div>
<div id="egg2" class="egg"> Egg1 </div>
<div id="egg2" class="egg"> Egg3 </div>

答案 1 :(得分:1)

If you want each baloon to show a random image when clicked try something like this:

[].slice
  //  find all divs containing an id containing baloon  
  .call(document.querySelectorAll('[id*=baloon]'))
  //  loop through all found divs 
  .map(function(baloon) {
    //  array of images to be randomized 
    var images = [
      'https://unsplash.it/100/?random=1',
      'https://unsplash.it/100/?random=2',
      'https://unsplash.it/100/?random=3',
      'https://unsplash.it/100/?random=4'
    ];

    //  pick a random image  
    var image = images[Math.floor(Math.random() * images.length)];

    //  add image to current baloon div 
    baloon.innerHTML = '<img src="' + image + '">';


    //  add click listener to baloon div 
    baloon.addEventListener('click', function() {

      //  pick a new random image
      var image = images[Math.floor(Math.random() * images.length)];

      //  add new image to current baloon div   
      baloon.innerHTML = '<img src="' + image + '">';

    })
  })
[id*="baloon"] {
  width: 100px;
  height: 100px;
  float: left;
  margin: 10px;
  border: 1px solid #ccc;
}
<div id="baloon1"></div>
<div id="baloon2"></div>
<div id="baloon3"></div>

In response to comment (please note I'm not an expert on php)

<?php
  //  print out images from dir to js array
  $images = array();
  foreach (glob("/IMAGEPATH/*.{jpg,png,gif}", GLOB_BRACE) as $filename) {
    $images[] = $filename;
  }
  echo "<script>var images=" . json_encode($images) . "</script>";
 ?>

答案 2 :(得分:0)

From what I understand you are looking for, you want to pass the baloon's div ID to Basket to only modify that div.

document.getElementById("baloon1").addEventListener("click", function(){Basket('baloon1');});
document.getElementById("baloon1").addEventListener("click", function(){Basket('baloon2');});
document.getElementById("baloon1").addEventListener("click", function(){Basket('baloon3');});

function Basket(divId){
    var dispImages = new Array ();
    dispImages[1] = "images/1.png";
    dispImages[2] = "images/2.png";
    dispImages[3] = "images/3.png";
    dispImages[4] = "images/4.png";
    var rnd = Math.floor( Math.random() * dispImages.length );
    if( rnd == 0 ) {rnd =1;}
    document.getElementById(divId).innerHTML = "<img src='" + dispImages[rnd] + "'/>";
}

答案 3 :(得分:0)

You can get all elements which id start with baloon like

var allElements = document.querySelectorAll('[id^="baloon"]')

for (var i = 0; i < allElements.length; i++) { 
    allElements[i].addEventListener('click', eggBasket)
}

function eggBasket(){
   console.log('clicked')
}
<div id="baloon1" >baloon1</div>
<div id="baloon2" >baloon2</div>
<div id="baloon3" >baloon3</div>