[英]Getting Unable to get property 'undefined' of undefined or null reference
I am having an issue with my code from javascript. 我的JavaScript代码有问题。 When I hit the button the function runs, but nothing happens on the screen.
当我按下按钮时,该功能运行,但屏幕上没有任何反应。 I went into the development tools for IE, and noticed that when I ran the script I got the following: Unable to get property 'undefined' of undefined or null reference.
我进入IE的开发工具,并注意到当我运行脚本时得到以下信息:无法获取未定义或空引用的属性“未定义”。 This stems from a else statement in the script of:
这源于以下脚本中的else语句:
function doSearch(){
var selectedItem = document.getElementsByName("engines").selectedIndex;
if (selectedItem == -1)
alert("You must select a search engine.");
else
location.href = document.getElementsByName("engines").option[selectedItem].value + document.getElementById("searchTerm").value;
}
I believe the code in the html to be right, but it just doesn't seem to work. 我相信html中的代码是正确的,但似乎似乎不起作用。 For example in the select list options for Google I have:
例如,在Google的选择列表选项中,我有:
<option value="http://www.google.com/search?q=">Google</option>
Anyone have any thoughts on what I might be doing wrong? 有人对我可能做错的事情有任何想法吗?
If the select is 如果选择是
<select name="engines">
then you need 那你需要
document.getElementsByName("engines")[0].selectedIndex
and 和
location.href = document.getElementsByName("engines")[0].option[selectedItem].value ...
since getElement s ByName returns a collection 因为getElement 的 ByName返回一个集合
If the select is 如果选择是
<select id="engines">
then you need 那你需要
document.getElementById("engines").selectedIndex
Additionally I would use 另外我会用
if (selectedItem < 1)
if I had a "please select" since the user could select the first option 如果我有一个“请选择”,因为用户可以选择第一个选项
Here is how I would likely code it (NOTE: Google does not work in an iFrame, but bing does) 这是我可能的编码方式(注意:Google在iFrame中不起作用,但bing可以)
window.onload=function() { document.getElementById("engines").onchange=function() { var engine = this.value; if (engine) { location.href = engine.replace("@",document.getElementById("searchTerm").value); } } }
<input id="searchTerm" type="text" /> <select id="engines"> <option value="">Please select</option> <option value="https://www.google.com/search?q=@">Google</option> <option value="https://www.bing.com/search?q=@">Bing</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.