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()}

如果我 alert stateName,我会得到一个反映我的选项选择的值。但是该stateName变量似乎并没有出现在changeBadgeViewandchangeCodeView函数中。我不明白为什么。有任何想法吗?

4

1 回答 1

3

您正在调用changeBadgeView并且changeCodeViewstateName分配其值之前。

你需要先完成任务...

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 回答