将eventListener添加到JavaScript中动态创建的“选择”框吗?

时间:2018-11-18 23:15:02

标签: javascript html event-listener

我正在尝试对动态创建的div中的动态创建的选择框进行编码,这两个均在页面加载时创建。我试图将onchange事件监听器添加到选择框的尝试仅在页面加载时触发,如何解决此问题?我是html和JavaScript的新手,所以我的代码是有目的的。这是我的代码:

function createDiv()
{
    var div = document.createElement('div');
    div.className = 'main-div';
    div.id = 'mainDiv';
    div.setAttribute('title', 'Main Div');
    var divText = document.createTextNode("Select a Number ");
    div.appendChild(divText);

    var select = document.createElement('select')

    select.options[0] = new Option("1");
    select.options[1] = new Option("2");
    select.options[2] = new Option("3");
    select.options[3] = new Option("4");
    select.options[4] = new Option("5");
    select.options[5] = new Option("6");
    select.options[6] = new Option("7");
    select.options[7] = new Option("8");
    select.options[8] = new Option("9");
    select.options[9] = new Option("10");

    //select.addEventListener("change", alert("changed!"));

    div.appendChild(select);


    document.body.appendChild(div);
    console.log(div);
}
<body onload = createDiv()>
    <h1 id = "heading1">Test</h1>
    <br>
    <script src="js/main.js"></script>
</body>

1 个答案:

答案 0 :(得分:1)

方法addEventListener在第二个参数中需要一个函数,并且您没有传递函数,而是传递了alert()函数的结果(无效)。

alert("changed!")更改为

function() {alert("changed!")}

(自ES6起可以缩短() => alert("changed!")

function createDiv() {
  var div = document.createElement('div');
  div.className = 'main-div';
  div.id = 'mainDiv';
  div.setAttribute('title', 'Main Div');
  var divText = document.createTextNode("Select a Number ");
  div.appendChild(divText);
  
  var select = document.createElement('select')
  for (var i = 1; i <= 10; i++) { 
    select.options[i] = new Option(i);
  }
  
  select.addEventListener("change", function() {alert("changed to "+select.value)});
  div.appendChild(select);
  document.body.appendChild(div);
}
<body onload = createDiv()>
  <h1 id = "heading1">Test</h1>
</body>