0

I hope someone can help me with some troubles I'm having. I'm working on a webshop in which it is possible to buy a product in multiple colours. I want to make a select box in which all available colours are stored and when you choose "Green" in the select box, the image of the product changes to the image of the product in green! I already made some sort of script that does what I want but I'm not satisfied yet.

All the available colours are loaded to the vars colours from a database, so it's pretty important to keep this part intact.

 var colours = {
     'red': 'http://i39.tinypic.com/2mgru6b.jpg',
     'blue':'http://i40.tinypic.com/5losqu.jpg',
 };

This is the img element in which the images are loaded into:

 <img src="http://i43.tinypic.com/2rw0v0m.jpg" id="preview-img">

And this is the function:

 window.showColour = function(colour) {
      var url = colours[colour];
      var img = document.getElementById('preview-img');
      img.src = url;
 };

Right now I'm calling the function by a simple link:

 <a href="javascript:showColour('red');">Red</a>
 <a href="javascript:showColour('blue')">Blue</a>

To see this all working: http://jsfiddle.net/92Ht6/5/

But the thing I want is that the function isn't being called by a simple link, I want the function to be executed when you select 'red' in the select box (showColour('red'); or when you select blue in the select box (showColour('blue');

Thanks in advance!

4

2 回答 2

2

考虑到您没有select,请创建一个,如下所示:

<select id='colors'>
    <option value='green'>Green</option>
    ..
    ..
</select>

然后onchange事件:

document.getElementById("colors").onchange = function() {
    var value = this.options[this.selectedIndex].value;
    showColour(value);
}

编辑:刚刚看到 jQuery 标签:\

于 2013-11-04T19:10:14.447 回答
1

使用change选择框中的事件:

<select id="colour">
  <option value="red">Nice red colour</option>
  <option value="blue">Cool blue colour</option>
</select>

jQuery绑定事件:

$(function(){
  $('#colour').change(function(){
    showColour($(this).val());
  });
});
于 2013-11-04T19:10:20.790 回答