使用onmouseover实现下拉菜单title标签时出现Uncaught TypeError错误求助
解决下拉菜单title绑定的TypeError问题
嘿,这个错误的原因很清晰——你把onmouseover事件绑定在了<form>元素上,但options和selectedIndex是<select>标签独有的属性,form元素根本没有这些东西,浏览器找不到对应属性自然就抛出Cannot read property 'undefined' of undefined错误啦!
问题根源分析
你原来的代码里,form标签上的这段代码:
onmouseover="this.title=this.options[this.selectedIndex].title"
这里的this指向的是当前的form元素,而不是你想要操作的select下拉框。form没有options集合,所以访问this.options就会得到undefined,再去访问undefined的selectedIndex自然就报错了。
修复方案
把鼠标悬停事件移到select元素上,因为只有select才拥有options和selectedIndex属性,这样this就能正确指向下拉框了:
修改后的完整表单代码:
<form name="searchform" onsubmit="return doSearch();" accept-charset="', $context['character_set'], '"> <input class="search_input" type="text" name="search" value="" /> <input class="search_button" type="submit" name="submit" value="" /> <select class="search_select" name="sengines" onchange="return saveOption();" onmouseover="this.title=this.options[this.selectedIndex].title"> <option value="?action=search2;search=" title="Full forum search">Forum</option> </select> </form>
进阶需求:鼠标悬停整个表单都显示title
如果你的需求是鼠标放到整个搜索表单(包括输入框、按钮)上都显示下拉框选中项的title,那可以保留form上的onmouseover事件,但要在事件里明确获取select元素:
<form name="searchform" onmouseover=" const select = this.querySelector('.search_select'); this.title = select.options[select.selectedIndex].title; " onsubmit="return doSearch();" accept-charset="', $context['character_set'], '"> <!-- 其他表单元素不变 --> </form>
这样就能通过form找到对应的select,再获取选中项的title赋值给form的title了。
内容的提问来源于stack exchange,提问作者greektranslator
相关产品推荐
相关产品推荐

