我有一个简单的选择框。当用户选择选项时,应显示包含某些代码的图像和文本框:
<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,我会得到一个反映我的选项选择的值。但是这个stateName变量似乎没有进入changeBadgeView和changeCodeView函数。我不明白为什么。有什么想法吗?
答案 0 :(得分: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;
}
}