将全局变量从下拉菜单选择传递给函数

Passing a global variable to a function from a dropdown menu selection

本文关键字:函数 选择 全局变量 下拉菜单      更新时间:2023-09-26

我有一个带有多个下拉菜单的程序,为了简单起见,每个菜单都存储在一个数组中。 我需要创建一个在选择新选项时激活的事件。这是我尝试过的:

  questionFormatList[counter] = document.createElement( "select" );
  questionFormatList[counter].id = counter;
  questionFormatList[ counter ].text = "Multiple Choice";
  //fill the dropdown menu with the four options
  for( var j = 0; j < 4; j++ )
  {
     questionFormatListOptions = document.createElement( "option" );
     dropDownMenuQuestionTextNode = document.createTextNode( questionTypes[ j ] );
     questionFormatListOptions.appendChild( dropDownMenuQuestionTextNode );
     questionFormatList[ counter ].appendChild( questionFormatListOptions );
  }
questionFormatList[counter].addEventListener( "change", function(){alteredSelection(questionFormatList[ counter ] );});

不过,它只是忽略了它。这三个变量是全局变量。请指教。我不是专业人士,所以也许这很简单。我假设这是听众的事情。

您正在最后创建的选择菜单上调用 addEventListener。 如果要调用所有三个选择菜单上的事件侦听器都会尝试。

selects = document.getElementsByTagName('select');
for( var j = 0; j < select.length; j++ )
{
  selects[i].addEventListener('change',function(){alteredSelection(selects[j])},false);
}

这将在所有选择上启用事件侦听器。 保持在控制台中查找问题的习惯,并使用控制台.log和 console.dir。它一直帮助着我。希望这有帮助。

如 Akurn 所示,您的问题是由于不正确地使用闭包范围变量计数器造成的。尝试使用此代码而不是最后一行:

(function(list) {
    list.addEventListener( "change", function() {
        alteredSelection(list);
    } );
})(questionFormatList[counter]);

这是在添加事件侦听器时questionFormatList[counter]其实际值的绑定结果。

顺便说一句:代码的第 3 行和第 4 行正在写入属性.text乘。