为select添加一个onchange事件

4

我有以下的js代码:

function createConBox() {
   var charDiv = document.getElementById("characterList");  // reference to "characterList" div
   header = document.createElement("p");  // creates the <p> tag
   charDiv.appendChild(header);  // adds the <p> tag to the parent node
   title = document.createTextNode("Show Only Lines By:");  // creates the text string
   header.appendChild(title); // adds the text string to the parent node

   // create select box and add elements
   selectBox = document.createElement("select");   
   selectBox.setAttribute("id", "cList");
   charDiv.appendChild(selectBox);

   charNames = uniqueElemText("h3");   // array of character names
   newOption = document.createElement("option");
   selectBox.appendChild(newOption);
   newOptionTitle = document.createTextNode("Show All Lines");
   newOption.appendChild(newOptionTitle);
   for (i = 0; i < charNames.length; i++) {
      newOption = document.createElement("option");
      selectBox.appendChild(newOption);
      newOptionTitle = document.createTextNode(charNames[i]);
      newOption.appendChild(newOptionTitle);
   }

}

function showLines() {
   alert("The Box has been changed");
}

每当选择框中的选项更改时,我希望它调用'showLines()'。然而,每次我尝试实现一个事件时,我只能在页面加载时触发它,以后再也无法触发。
3个回答

4

selectBox.onchange = showLines;应该可以解决你的问题。

在某些浏览器中,onchange事件只有在选择框失去焦点之后才会触发。为了克服这个问题,你可以使用onclick代替onchange


3

我猜你正在这样做:

selectBox.onchange = showLines();

如果是这种情况,只需删除()即可:
selectBox.onchange = showLines;

0

当我动态传递id时,我该怎么做:

var selectcell = tablerow.insertCell(1);
var selectelmt = document.createElement('select');
selectelmt.name = 'Select';
selectelmt.value = 'select';
selectelmt.classList = 'form-control input-sm cobclass';
selectelmt.onchange= onselectchange(i);
selectelmt.id = 'cobselect' + i;
selectelmt.options[0] = new Option('select');
selectcell.appendChild(selectelmt);
// ddrbind(i);
show();
i++;`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接