2013-09-30 56 views
0

此earler代碼工作fine.but不知道突然停止工作..更改位置代碼後。JavaScript的一些如何停止工作

give error : 
- Uncaught TypeError: Cannot read property 'options' of undefined (in chrome) 
- no element found (in firefox) 

var inputs = document.getElementsByTagName("select"); //get array of select tag 

var sSrnti = inputs[0].options[inputs[0].selectedIndex].value; //get selected value of first list 

var sType = inputs[1].options[inputs[1].selectedIndex].value;//get selected value of second list 

var sStatus = inputs[2].options[inputs[2].selectedIndex].value;//get selected value of third list 

請幫助我..謝謝

+0

你從哪裏移動代碼並將它放在哪裏? – jeff

+0

至少有一個'input [0]','inputs [1]',inputs [2]'出現'null'。我猜測,在執行代碼的時間或上下文中,元素不存在於DOM中。 –

+0

我想到的第一件事就是您已將腳本移動到實際的html之上。這會導致它在你的dom樹被加載之前運行,因此爲''document.getElementsByTagName(「select」);''返回'undefined',導致下一行出現錯誤。 – Kippie

回答

0

我不明白你的意思由

"after changing location for code" 

你應該對更加清晰。但正如kippie在上面評論的那樣,你最有可能將調用你的js文件的script標籤移到html之上。 下面是HTML

<!DOCTYPE html> 
<html> 
    <head> 
     <title>some title</title> 
     <!-- add all refs to css files here taking note of the cascading property of css--> 
     <link href="..." rel="stylesheet"> 
    </head> 

    <body> 

    </body> 
    <!-- add all calls to js files here, so you can be sure dom is loaded--> 
    <script src="somefile.js"></script> 
</html> 

推薦的佈局。如果你這樣做了,問題依然存在,讓我知道什麼樣的代碼你感動,在這裏你移動它。 您也可以使用Chrome控制檯嘗試獲取代碼。 e.g

press control + shift + j on your keyboard 

,並使用相同的命令如的document.getElementById(「#ID」),看看是否會工作,這時我們可以看到什麼是錯的。

祝你好運。

+0

這真的幫助我謝謝.. – Piyush

+0

高興的幫助 - :) –

0

如果你有一個看起來像這樣的選擇元素:

<select id="ddlViewBy"> 
<option value="1">test1</option> 
<option value="2" selected="selected">test2</option> 
<option value="3">test3</option> 
</select> 

運行此代碼:

var e = document.getElementById("ddlViewBy"); 
var strUser = e.options[e.selectedIndex].value; 

是否會讓strUser的是2.如果你真正想要的是test2,那麼這樣做:

var e = document.getElementById("ddlViewBy"); 
var strUser = e.options[e.selectedIndex].text; 
0

要麼在HTML中沒有至少三個select元素,要麼您的JavaScript在DOM加載之前觸發。

嘗試以下...

<script type="text/javascript"> 
    window.onload = function() { 
    // Your JavaScript here... 
    } 
</script>