使用SELECT元素加载图像

时间:2015-10-09 09:48:54

标签: javascript html

我有这个html代码可以正常工作。我想在选择一个选项时加载该标志的图像,然后使用我的数据库的选项值。

<form method="post" id="countriesForm" name="countriesForm" enctype="application/x-www-form-urlencoded">
<select id="select1" onchange="changeTest()" name="select1">
    <option value="0">USA</option>
    <option value="1">AUSTRALIA</option>
    <option value="2">CANADA</option>
</select>
</form>
<img id="flags" height="30" width="50" border="0" name="flags"></img> 

imageArray = new Array("usa.gif", "australia.gif", "canada.gif");
altArray = new Array("USA", "AUSTRALIA", "CANADA");

function changeTest () 
{ 
    var Index = document.countriesForm.select1.options[document.countriesForm.select1.selectedIndex].value;
    document.flags.src = imageArray[Index]; document.flags.alt = altArray[Index];   
}

2 个答案:

答案 0 :(得分:1)

这样就可以了。这是demo

<强> HTML

<form method="post" id="countriesForm" name="countriesForm" enctype="application/x-www-form-urlencoded">
<select id="select1" name="select1">
    <option value="0">USA</option>
    <option value="1">AUSTRALIA</option>
    <option value="2">CANADA</option>
</select>
</form>
<img id="flags" height="30" width="50" border="0" name="flags"></img> 

<强> JS

(function(){
 var imageArray = new Array("usa.gif", "australia.gif", "canada.gif");
var altArray = new Array("Default", "Round", "Frame", "Pink Star");

    document.getElementById('select1').onchange = function() {
        var e = document.getElementById('select1');
        var index = e.options[e.selectedIndex].value;
        var targetImg = document.getElementById('flags');
        targetImg.src = imageArray[index];
        targetImg.alt = altArray[index];   
    };
})();

答案 1 :(得分:0)

这样做:

document.getElementById('select1').onchange = function() {
    var index = this.options[this.selectedIndex].value;
    document.flags.src = imageArray[index];
    document.flags.alt = altArray[index];
    //alert(imageArray[index]);
};

http://jsfiddle.net/5dkdm5ge/1/