シンプルなセレクトボックスがあります。ユーザーがオプションを選択すると、画像とコードを含むテキスト ボックスが表示されます。
<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
に到達していないようです。理由がわかりません。何か案は?changeBadgeView
changeCodeView