0

このスクリプトをオンラインで見つけました。それは私が必要とするほとんどのものです。見てみましょう:

<script type="text/javascript">
    imageArray = new Array("NOimglink", "imglink", "imglink", "imglink");
    altArray = new Array("", "Red Star", "Yellow Star", "Pink Star");

    function show() {
        var Index = document.menuForm.select1.options[document.menuForm.select1.selectedIndex].value;
        var text = document.getElementById('select1').options[document.getElementById('select1').selectedIndex].text;
        document.testStar.src = imageArray[Index];
        document.testStar.alt = altArray[Index];
        document.getElementById("item").innerHTML = document.getElementById("select1").value;
    }
</script>
<div id="item"></div>
<form action="../action/return.html" method="post" id="menuForm" name="menuForm">
    <select id="select1" onchange="show()" name="select1">
        <option value="0" selected="selected">Choose a color</option>
        <option value="1">Red Star</option>
        <option value="2">Yellow Star</option>
        <option value="3">Pink Star</option>
    </select>
    <img id="testStar" height="35" alt="red star" src="" width="35" border="0" name="testStar">

とにかく、すべての配列行を使用する以外に方法はありますか? imageArray と altArray ? 50 を超える選択オプションがありますが、配列が多すぎます。もっと簡単な方法はありますか?

4

2 に答える 2

0

すべての配列を避けたい場合は、HTML を少し変更する必要があります。配列は key-val ルックアップとして機能し、それがなければ、前の val スポットに val を設定する必要があります。つまり、次のようにoption values をイメージ src と等しくします。

<option value="" selected="selected">Choose a color</option>
<option value="imgLink.png">Red Star</option>
<option value="imgLink2.png">Yellow Star</option>
<option value="img3.jpg">Pink Star</option>

option valueを新しいソースに設定しoption text、代替テキストとして使用するだけです。

function show() {
    var elemSel = document.getElementById('select1'),
        testStar = document.getElementById("testStar"),
        newSrc = elemSel.options[ elemSel.selectedIndex ].value,
        newAlt = elemSel.options[ elemSel.selectedIndex ].text;
    testStar.src = newSrc;
    testStar.alt = newAlt;
    document.getElementById("item").innerHTML = "Src: "+newSrc+"  |Alt: "+newAlt;
}

http://jsfiddle.net/daCrosby/JkhxP/1/

編集

値にファイル拡張子を含めたくない場合は、削除してください:

<option value="" selected="selected">Choose a color</option>
<option value="imgLink">Red Star</option>
<option value="imgLink2">Yellow Star</option>
<option value="img3">Pink Star</option>

新しい src の完全なリンクが必要な場合は、次のように追加します。

var elemSel = document.getElementById('select1'),
    newSrc = elemSel.options[ elemSel.selectedIndex ].value;
newSrc = "example.com/img/" + newSrc + ".png";

http://jsfiddle.net/daCrosby/JkhxP/2/

于 2013-08-11T20:08:43.937 に答える