在不同的元素

时间:2017-05-06 22:21:58

标签: javascript arrays

我正在尝试在我的应用程序中设置一个功能,允许用户单击按钮,然后单击显示图像的提交按钮,但我希​​望按钮可以容纳多个图像并随机选择一个图像来自阵列。

我该怎么做?

    <div id='prefPage'>

    <header id='header2pref'>

    <div id='title2pref'>PREFERENCES</div>
    
    </header>

    <div id='body'>
    <div id='leftAlign'>
    <div id="foodpicloc">



    </div>
           
           
         
    </div><button id='myBtn2'>SET PREFRENCES</button>


      
    <div id='rightAlignPref'>

    <div id=fixed>

    <div>
    
    <button id="button1">BURGER</button>
    <button id="button2">HOTDOG</button>

    </div>
                
    </div>

    </div>

    </div>

    </div>



var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");

var preference = document.getElementById("preference");
var foodpic = document.getElementById("foodpiclocation");
var foodpic;

button1.addEventListener('click', function() {
  foodpicurl = 'burger.svg';
});

button2.addEventListener('click', function() {
  foodpicurl = 'hotdog.svg';
});

preference.addEventListener('click', function() {
  var foodpic = document.createElement('img');
  foodpic.src = foodpicurl;

  foodpiclocation.innerHTML = '';
  foodpiclocation.appendChild(foodpic);
});

1 个答案:

答案 0 :(得分:0)

使用vanilla Javascript清洁解决方案。注意:我建议您先在HTML中添加HTML代码<div id="foodpicloc"><img id="foodpic"></div>。更改图像的src比每次图像更改时附加新的图像元素更快更干净。

<强>定义

function mapClickToImage(imageSelector, updateBtnSelector, btnSectorToImageSrcMapping) {

  var currentImageSrc = null;
  var imageElement = document.querySelector(imageSelector);
  for (var btnSelector in btnSectorToImageSrcMapping) {

    var buttonElement = document.querySelector(btnSelector);
    buttonElement.addEventListener('click', function() {
    currentImageSrc = btnSectorToImageSrcMapping[btnSelector];
  });

  var updateButtonElement = document.querySelector(updateBtnSelector);
  updateButtonElement.addEventListener('click', function() {
    if (currentImageSrc) {
      imageElement.src = currentImageSrc;
    }
  });
}

<强>用法

mapClickToImage('#foodpic', '#preference', {
  '#button1': 'burger.svg',
  '#button2': 'hotdog.svg'
});