0

シンプルなセレクトボックスがあります。ユーザーがオプションを選択すると、画像とコードを含むテキスト ボックスが表示されます。

 <select name="state" id="state" style="margin-bottom: 1em;">
      <option value="AL">Alabama</option>
      <option value="AK">Alaska</option>
      <option value="AZ">Arizona</option>
      <!-- etc. etc. -->
 </select>
 
 <div id="badgeView"></div>
 
 <div id="codewrap" >
      <textarea id="codeView" readonly="readonly"></textarea>
 </div>

スクリプトは次のとおりです。

/* Helpful variables */ 
var codeTemplate = '<a href="http://www.nonprofitvote.org/voting-in-yourstate.html" title="Voting in Your State">\n' + '<img src="http://nonprofitvote.org/images/badges/voting_in_yourstate.jpg" alt="Voting in Your State" />\n' + '</a>';
var state = document.getElementById('state');
var badgeView = document.getElementById('badgeView');
var codeView = document.getElementById('codeView');

/* Load up AL's image and code when the page first loads */
changeBadgeAndCode();

/* What to do when the user selects an option */
state.addEventListener('change', changeBadgeAndCode, false);

/* What to do if a user clicks in the code view text box */
codeView.addEventListener('click', selectText, false);

/* Function declarations */
function changeBadgeAndCode(){
    changeBadgeView(badgeView);
    changeCodeView(codeView);

    var stateName = state.options[state.selectedIndex].value.toLowerCase();

    function changeBadgeView(element) {
        element.innerHTML = '<img src="http://www.nonprofitvote.org/images/badges/voting_in_' + stateName + '.jpg" />';
    }

    function changeCodeView(element) {
        codeTemplate = codeTemplate.replace(/yourstate/g, stateName);
        codeTemplate = codeTemplate.replace(/Your State/g, stateName);
        element.innerHTML = codeTemplate;
    }
}
function selectText(){this.select()}

アラートstateNameを出すと、オプションの選択を反映した値が得られます。しかし、その変数はand関数stateNameに到達していないようです。理由がわかりません。何か案は?changeBadgeViewchangeCodeView

4

1 に答える 1

3

を呼び出してchangeBadgeViewおり、その値が割り当てられるchangeCodeView前です。stateName

まず宿題をやらなきゃ…

function changeBadgeAndCode(){
    var stateName = state.options[state.selectedIndex].value.toLowerCase();

    changeBadgeView(badgeView);
    changeCodeView(codeView);

    function changeBadgeView(element) {
        element.innerHTML = '<img src="http://www.nonprofitvote.org/images/badges/voting_in_' + stateName + '.jpg" />';
    }

    function changeCodeView(element) {
        codeTemplate = codeTemplate.replace(/yourstate/g, stateName);
        codeTemplate = codeTemplate.replace(/Your State/g, stateName);
        element.innerHTML = codeTemplate;
    }
}
于 2012-07-22T22:35:36.227 に答える