javascript:根据选择框值显示图片

时间:2017-10-20 22:43:50

标签: javascript

在我的程序中,我创建了选择框和按钮。从选择框图像中选择不同的值时,应按预期输出显示。前后两个按钮可以更改图像。哪个也应该有效。我在下面创建了代码,但我的代码没有按预期工作。任何人都可以帮助我吗?

代码:



// counter
var i = 0;

// create object
imageObj = new Image(128, 128);

// set image list
images = new Array();
images[0] = "final_images/wcoat.jpg";
images[1] = "final_images/wcoat.jpg";
images[2] = "final_images/ktoys.jpg";
images[3] = "final_images/mixture.jpeg";
images[4] = "final_images/earing.jpg";

var imgLen = imageObj.length;

var go = document.getElementById('go');
go.addEventListener("click", loadItem);

function loadItem() {

  var mainDiv = document.getElementById("main");

  var btnPre = document.createElement("input");
  //Assign different attributes to the element. 
  btnPre.type = "button";
  btnPre.value = "previous";
  btnPre.id = "preBtn";

  mainDiv.appendChild(btnPre);

  preBtn.addEventListener('click', prvs);

  var holder = document.getElementById("holder");

  if (document.getElementById('selectBox').value == "womens") {
    holder.src = images[0] + "<br>" + " Women's coat";
  } else if (document.getElementById('selectBox').value == "mens") {
    holder.src = images[1] + "<br>" + " Men's coat";
  } else if (document.getElementById('selectBox').value == "kids") {
    holder.src = images[2] + "<br>" + " Kid's toys";
  } else if (document.getElementById('selectBox').value == "mixture") {
    holder.src = images[3] + "<br>" + " Classic mixture";
  } else if (document.getElementById('selectBox').value == "earing") {
    holder.src = images[4] + "<br>" + " Gold Earing";
  }

  var btnNxt = document.createElement("input");
  //Assign different attributes to the element. 
  btnNxt.type = "button";
  btnNxt.value = "next";
  btnNxt.id = "nxtBtn";

  mainDiv.appendChild(btnNxt);

  nxtBtn.addEventListener('click', nxt);
}

function nxt() {
  if (i < imgLen - 1) {
    i++;
  } else {
    i = 0;
  }

  imageObj.src = images[i];
}

function prvs() {
  if (i > 0) {
    i--;
  } else {
    i = imgLen - 1;
  }
  imageObj.src = images[i];
}
&#13;
body {
  background-image: url("final_images/back.jpg");
}

.container {
  /*width: 600px;*/
  /*height: 200px;*/
  border: inset;
  background-color: rgba(255, 234, 134, 0.9);
}

#selectBox {
  margin-left: 210px;
  width: 160px;
}

#below_hr {
  width: 600px;
  background-color: #ffffff;
}

#preBtn {
  margin-left: 170px;
  margin-top: 170px;
}
&#13;
<div class='container' id="main">
  <form name="myForm">
    <select name="mySelect" id="selectBox">
        				<option value="womens">Women's coat</option>
        				<option value="mens">Men's coat</option>
        				<option value="kids">Kid's toys</option>
        				<option value="mixture">Classic mixture</option>
        				<option value="earing">Gold Earing</option>
        			</select>
    <INPUT TYPE="button" VALUE="Go" id="go">
    </INPUT>
  </form>
  <HR size="4" color="red" id="hr">

  <div id="holder"> </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

有一些微小的错误加起来不起作用,我会尝试记住并指出它们。这是一个工作示例,只有2张图片 - 您可以填写

  1. 你的形象有一个div&#34; holder&#34;这应该是<img /> 标签
  2. var imgLen = imageObj.length;应该var imgLen = images.length;使用数组的长度而不是obj。
  3. preBtn.addEventListener应为btnPre. preBtn不存在
  4. holder.src = images[0] + "<br>" + " Women's coat"; src属性需要是一个有效的网址,当你追加<br>及其字符串时,你就会搞乱它。
  5. imageObj.src=images[i];需要引用您的&#34;持有者&#34;不是imageObj所以它应该是document.getElementById("holder").src = images[i];
  6. 您不需要动态地将每个图像加载下一个和上一个按钮(您甚至不能清除它们),因此DOM会不断堆积按钮。
  7. 您应该使用数字作为值,这样您就可以将select设置为next和prev
  8. 上的正确描述
  9. 当用户跳过选择(在选择更改时设置i)时,您需要跟踪i
  10. &#13;
    &#13;
    // counter
    var i = 0;
    
    // create object
    imageObj = new Image(128, 128);
    
    // set image list
    images = new Array();
    images[0] = "https://cdn-image.myrecipes.com/sites/default/files/summer-sweet-lemonade-cl.jpg";
    images[1] = "http://www.greatamericancookies.com/app/themes/greatamericancookies/library/images/home/carousel3.png";
    images[2] = "final_images/ktoys.jpg";
    images[3] = "final_images/mixture.jpeg";
    images[4] = "final_images/earing.jpg";
    
    var imgLen = images.length;
    
    var go = document.getElementById('go');
    var select = document.getElementById('selectBox');
    var desc = document.getElementById('desc');
    go.addEventListener("click", loadItem);
    
    function loadItem() {
      var holder = document.getElementById("holder");
    
      if (document.getElementById('selectBox').value == 0) {
        holder.src = images[0];
        desc.innerHTML = document.getElementById("select0").getAttribute("data-desc");
        i = 0;
      } else if (document.getElementById('selectBox').value == 1) {
        holder.src = images[1];
        desc.innerHTML = document.getElementById("select1").getAttribute("data-desc");
        i = 1;
      } else if (document.getElementById('selectBox').value == 2) {
        holder.src = images[2];
        desc.innerHTML = document.getElementById("select2").getAttribute("data-desc");
        i = 2;
      } else if (document.getElementById('selectBox').value == 3) {
        holder.src = images[3];
        desc.innerHTML = document.getElementById("select3").getAttribute("data-desc");
        i = 3;
      } else if (document.getElementById('selectBox').value == 4) {
        holder.src = images[4];
        desc.innerHTML = document.getElementById("select4").getAttribute("data-desc");
        i = 4;
      }
      document.getElementById('prev').style.display = "";
      document.getElementById('next').style.display = "";
    }
    
    function nxt() {
      if (i < imgLen - 1) {
        i++;
      } else {
        i = 0;
      }
      select.value = i;
      desc.innerHTML = document.getElementById("select" + i).getAttribute("data-desc");
      document.getElementById("holder").src = images[i];
    }
    
    function prvs() {
      if (i > 0) {
        i--;
      } else {
        i = imgLen - 1;
      }
      select.value = i;
      desc.innerHTML = document.getElementById("select" + i).getAttribute("data-desc");
      document.getElementById("holder").src = images[i];
    }
    &#13;
    body {
      background-image: url("final_images/back.jpg");
    }
    
    img {
      width: 200px;
    }
    
    .container {
      /*width: 600px;*/
      /*height: 200px;*/
      border: inset;
      background-color: rgba(255, 234, 134, 0.9);
    }
    
    #selectBox {
      margin-left: 210px;
      width: 160px;
    }
    
    #below_hr {
      width: 600px;
      background-color: #ffffff;
    }
    
    #preBtn {
      margin-left: 170px;
      margin-top: 170px;
    }
    &#13;
    <div class='container' id="main">
      <form name="myForm">
        <select name="mySelect" id="selectBox">
        				<option id="select0" data-desc="a womans coat" value=0>Women's coat</option>
        				<option id="select1" data-desc="a mens winter coat" value=1>Men's coat</option>
        				<option id="select2" data-desc="a kids toy to play with" value=2>Kid's toys</option>
        				<option id="select3" data-desc="a classic mixture" value=3>Classic mixture</option>
        				<option id="select4" data-desc="a beautiful gold earing" value=4>Gold Earing</option>
        			</select>
        <INPUT TYPE="button" VALUE="Go" id="go">
        </INPUT>
      </form>
      <HR size="4" color="red" id="hr">
    
      <img id="holder" /><br/>
      <span id="desc"></span><br/><br/>
      
      <button id="prev" onclick="prvs()" style="display:none">Previous</button>
      <button id="next" onclick="nxt()" style="display:none">Next</button>
    </div>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:2)

你的代码中有很多错误,安德鲁(+1代表)已在他的答案中列出了这些错误。 但我认为你也许应该尝试更加动态,并从例如配置对象中创建选择。

以下是一个例子:

&#13;
&#13;
// CLASS
var ImageSelector = (function(doc) {
  // private variables
  var _config,
      _selectionEl, 
      _imageEl,
      _prevBtnEl,
      _nextBtnEl,
      _currentIndex = 0;
  
  // constructor
  function ImageSelector(config) {
    var imageholderEl = doc.querySelector(config.imageholder);
    _config = config;
    _selectionEl = doc.querySelector(config.selection);
    _prevBtnEl = doc.querySelector(config.prevBtn);
    _nextBtnEl = doc.querySelector(config.nextBtn);
    if(!_selectionEl || !imageholderEl) {
      throw new Error('no selection or imageholder element found');
    }
    _imageEl = new Image();
    imageholderEl.appendChild(_imageEl);
    _generateSelection();
    _bindEvents();
  }
  
  // private methods
  function _generateSelection() {
    var fragment = doc.createDocumentFragment();
    var items = _config.items;
    
    for(var i = 0; i < items.length; ++i) {
      var item = items[i];
      var option = doc.createElement('option');
      option.value = item.value;
      option.textContent = item.name;
      fragment.appendChild(option);
    }
    _selectionEl.appendChild(fragment);
    _selectionEl.selectedIndex = _currentIndex;
  }

  function _loadImage() {
    var items = _config.items;
    var item = items.find(itm => itm.value === _selectionEl.value);
    _imageEl.src = item.image;
    _prevBtnEl.style.display = null;
    _nextBtnEl.style.display = null;
  }
  
  function _bindEvents() {
    var goBtnEl = doc.querySelector(config.goBtn);  
    _selectionEl.addEventListener('change', _loadImage);
    if(_prevBtnEl) {
      _prevBtnEl.addEventListener('click', ImageSelector.prototype.prev);
      _prevBtnEl.style.display = 'none';
    }
    if(_nextBtnEl) {
      _nextBtnEl.addEventListener('click', ImageSelector.prototype.next);
      _nextBtnEl.style.display = 'none';
    }   
    goBtnEl && goBtnEl.addEventListener('click', _loadImage)
  }
  
  function _changeIndex(direction) {
    var length = _config.items.length;
    _currentIndex = (_currentIndex + direction) % length;
    if(_currentIndex < 0) _currentIndex = length -1;
    _selectionEl.selectedIndex = _currentIndex;
    _selectionEl.dispatchEvent(new Event('change'));
  }
  
  // public methods
  ImageSelector.prototype.next = function() {
    _changeIndex(1);
  }

  ImageSelector.prototype.prev = function() {
    _changeIndex(-1);
  }

  return ImageSelector;
})(document);


// CONFIGURATION
var config = {
  selection: '#selectBox',
  imageholder: '#holder',
  goBtn: '#go',
  prevBtn: '#prev',
  nextBtn: '#next',
  items: [
    { name: "Women's coat", value: "womens", image: "https://thumb7.shutterstock.com/display_pic_with_logo/562036/116906134/stock-photo-portrait-of-brown-eyed-cat-isolated-on-white-background-116906134.jpg" },
    { name: "Men's coat", value: "mens", image: "https://thumb1.shutterstock.com/display_pic_with_logo/154447/235089946/stock-photo-cute-little-red-kitten-sleeps-on-fur-white-blanket-235089946.jpg" },
    { name: "Kid's toys", value: "kids", image: "https://thumb9.shutterstock.com/display_pic_with_logo/2288597/574871668/stock-photo-brown-cat-playing-relaxed-on-the-mobile-574871668.jpg" },
    { name: "Classic mixture", value: "mixture", image: "https://thumb9.shutterstock.com/display_pic_with_logo/4363153/520870675/stock-photo-lovely-cat-in-human-hands-vintage-effect-love-for-the-animals-520870675.jpg" },
    { name: "Gold Earing", value: "earing", image: "https://thumb9.shutterstock.com/display_pic_with_logo/428239/454556905/stock-photo-happy-scottish-kitten-looking-at-camera-isolated-on-white-background-454556905.jpg" }
  ]
}

// INITIALISATION
var selector = new ImageSelector(config);
&#13;
body {
  background-image: url("final_images/back.jpg");
}

img {
  width: 200px;
}

.container {
  /*width: 600px;*/
  /*height: 200px;*/
  border: inset;
  background-color: rgba(255, 234, 134, 0.9);
}

#selectBox {
  margin-left: 210px;
  width: 160px;
}

#below_hr {
  width: 600px;
  background-color: #ffffff;
}

#preBtn {
  margin-left: 170px;
  margin-top: 170px;
}
&#13;
<div class='container' id="main">
  <form name="myForm">
    <select name="mySelect" id="selectBox">
      
    </select>
    <input type="button" value="Go" id="go" />
  </form>
  <hr size="4" color="red" id="hr" />

  <div id="holder"></div>
  
  <button id="prev">Previous</button>
  <button id="next">Next</button>
</div>
&#13;
&#13;
&#13;

相关问题