onchange不适用于下拉菜单?

时间:2013-12-16 00:43:15

标签: javascript html

我正在尝试这样做,以便当从我的下拉菜单中进行选择时,文本将相应地显示在我的textarea中,因为现在我一直试图让其中一个工作。

问题:它不会显示textarea中数组的字符串。这段代码中存在问题吗?

下拉菜单:

<select id="dropdown" onchange="getFrames();">
    <option value="1" selected="selected"> Blank </option>
    <option value="2"> Exercise </option>
    <option value="3"> Juggler </option>
    <option value="4"> Bike </option>
    <option value="5"> Dive </option>
</select>

textarea:

<textarea id="textstage" rows="80" cols="20"> </textarea>

JavaScript:

我有这些全局变量。

var theStage = document.getElementById("textstage");
var getDrop = document.getElementById("dropdown");

然后我有这个功能。

function getFrames(){
    var dropSel = getDrop.options[getDrop.selectedIndex].value;

    if(dropSel === 2){
        theStage.value = ANIMATIONS["Exercise"];
}

被引用的数组是来自另一个js文件的全局数组。

2 个答案:

答案 0 :(得分:3)

尝试:

var theStage,getDrop; 

function getFrames() {
    var dropSel = getDrop.options[getDrop.selectedIndex].innerHTML;//+getDrop.value;
    theStage.value = ANIMATIONS[dropSel];

}

//Place the selection part on load callback
window.onload = function () {
    theStage = document.getElementById("textstage");
    getDrop = document.getElementById("dropdown");
}

<强> Demo

  • 您可以使用getDrop.value代替getDrop.options[getDrop.selectedIndex].value
  • ===是严格的平等比较,意思是“2”=== 2将在您的情况下为假。
  • 好像你正在寻找选项文本来查找基于此值的值作为对象动画中的键。所以你可以getDrop.options[getDrop.selectedIndex].innerHTML
  • 您的文档选择代码应位于window.onload内或html
  • 中的元素之后

答案 1 :(得分:0)

我通过省略内联事件处理程序对您的html做了一些小改动,而是将其添加到了javascript中。

<强> HTML:

<select id="dropdown">
    <option value="1" selected="selected"> Blank </option>
    <option value="2"> Exercise </option>
    <option value="3"> Juggler </option>
    <option value="4"> Bike </option>
    <option value="5"> Dive </option>
</select>
<textarea id="textstage" rows="80" cols="20"> </textarea>

另外,在javascript中,我拿走了严格的相等(===)并且只是(==)。

<强>的javascript:

var theStage = document.getElementById("textstage");
var getDrop = document.getElementById("dropdown");
getDrop.addEventListener("change",getFrames);
function getFrames(){
   var dropSel = getDrop.options[getDrop.selectedIndex].value;
    if(dropSel == 2){
      theStage.value = ANIMATIONS["Exercise"];
    }
}

希望它现在适合你。