我生成的下拉菜单适用于Firefox和IE,但不适用于Google Chrome。我有
function characterList(){
//code removed that generates select list
var optionContainer = document.createElement("option");
optionContainer.innerHTML = "Show All Character Lines";
addEvent(optionContainer, "click", filterChar, false);
selectContainer.appendChild(optionContainer); //appends option to select menu
for (var i = 0; i < menu_lines; i++){
var optionContainer1 = document.createElement("option");
optionContainer1.innerHTML = "blah" //simplified so that names in menu are all "blah"
selectContainer.appendChild(optionContainer1);//appends option to select menu
addEvent(optionContainer1, "click", filterChar, false);//I think the problem is here.
}
}
function filterChar(){
alert("filterChar");
}
function addEvent(object, evName, fnName, cap) {
if (object.attachEvent)
object.attachEvent("on" + evName, fnName);
else if (object.addEventListener)
object.addEventListener(evName, fnName, cap);
}
characterList填充一个下拉菜单(选择选项类型),其名称取自HTML文件的h3标题。这很好用。问题是,在谷歌浏览器中,过滤菜单点击不会调用过滤器。我有一个给我的函数(attachEvent),它应该是全浏览器兼容的。请有人帮忙。
答案 0 :(得分:0)
您需要将单个事件侦听器附加到select
元素。选项元素不是常规DOM元素,这就是为什么收听onclick
不起作用的原因。
当选择发生变化时,会向选择中附加一个onchange
事件侦听器:
addEvent(selectContainer, "change", filterChar, false);
您可以使用作为第一个参数传递的事件对象来引用回调函数中的select:
function filterChar(e){
var select = e.target;
alert("The selected item was index "+select.selectedIndex);
}