2017-09-02 73 views
2

我有我的JavaScript函數在JavaScript文件,因爲此功能使用我的大部分頁面。Javascript無法找到元素ID

function setSecondaryItem() { 
var select = document.getElementById("<%= SecondaryArea.ClientID %>"); 
var len = select.length; 
... 
...} 

我也把這個在我的網頁

<script type="text/javascript" src="../NormalUseFuction.js"></script> 

我調用此函數當下拉列表改變

<asp:DropDownList runat="server" ID="PrimaryArea" onchange="setSecondaryItem()" > 
    <asp:ListItem Value="" Text="select..." Selected="True"></asp:ListItem> 
    <asp:ListItem Value="A" Text="A.."></asp:ListItem> 
    <asp:ListItem Value="B" Text="B.."></asp:ListItem> 
    <asp:ListItem Value="D" Text="D.."></asp:ListItem> 
    <asp:ListItem Value="E" Text="E.."></asp:ListItem> 
    <asp:ListItem Value="F" Text="F.."></asp:ListItem> 
    </asp:DropDownList> 
<asp:DropDownList runat="server" ID="SecondaryArea" > 
    <asp:ListItem Value="1" Text="1.."></asp:ListItem> 
    <asp:ListItem Value="2" Text="2.."></asp:ListItem> 
    <asp:ListItem Value="3" Text="3.."></asp:ListItem> 
    <asp:ListItem Value="4" Text="4.."></asp:ListItem> 
    <asp:ListItem Value="5" Text="5.."></asp:ListItem> 
</asp:DropDownList> 

但是我發現,這會得到一個錯誤:遺漏的類型錯誤:不能讀取屬性'長度'null

任何人都可以告訴我如何解決這個問題?

注意:實際上是頁面中的兩個下拉列表。更改dropdownlist1將調用該函數來更改dropdownlist2。

+0

發表您的HTML上面 – Sajeetharan

+1

做一個視圖源檢查在客戶端產生的seconday區域的ID,並匹配它在功能上。我不認爲它已經正確呈現在js文件中。將次區域客戶端ID作爲參數傳遞給setSecondaryItem()函數,如'<%= SecondaryArea.ClientID%>'。 – Amit

+0

我已更新我的html –

回答

1

您使用的這個<%= SecondaryArea.ClientID %>被稱爲Code Block。 你也可以參考this question在stackoverflow更多細節。

代碼塊不能放在外部JavaScript文件中,因爲它們需要呈現爲C#代碼。

由於您的JavaScript函數setSecondaryItem在許多頁面中使用,當然重複它並不好,所以您需要在外部JavaScript文件中定義您的函數,並將您的代碼塊(在您需要的任何頁面中)一個論點。

您的外部JavaScript文件:

function setSecondaryItem(secondaryAreaId) { 
    var select = document.getElementById(secondaryAreaId); 
    var len = select.length; 
    ... 
} 

而在你.aspx文件:

<script type="text/javascript" src="../NormalUseFuction.js"></script> 

<script type="text/javascript"> 
    setSecondaryItem("<%= SecondaryArea.ClientID %>"); 
</script> 
+1

這項工作後,無法讀取屬性'選項'null!謝謝。 –

0

select.length你應該得到項目的長度,如果仍然沒有嘗試下面的代碼行,可能會幫助你。

select.options.length 
+0

我收到一個錯誤:嘗試此 –