onchange不适用于下拉菜单



我正在尝试这样做,当从下拉菜单中进行选择时,文本将相应地显示在我的文本区域内,目前我一直在尝试让其中一个工作。

问题:它不会在文本区域内显示数组中的字符串。问题是否在此代码中?

下拉菜单:

<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 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文件中的全局数组。

尝试:

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");
}

演示

  • 您可以只使用getDrop.value而不使用getDrop.options[getDrop.selectedIndex].value
  • ===是严格的相等比较,意味着在您的情况下"2"===2将为false
  • 似乎您正在寻找选项文本,以查找基于此的值作为对象动画中的关键点。所以你可以做getDrop.options[getDrop.selectedIndex].innerHTML
  • 您的文档选择代码应该在window.onload内或html中的元素之后

我省略了内联事件处理程序,而是将其添加到javascript中,从而对html做了一个小的更改。

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"];
    }
}

希望它现在对你有用。

最新更新