2010-06-25 101 views
0

加載時我都調用了一個JavaScript setTimeout()函數,該函數將隱藏.NET Panel控件,並在第一次加載後將其隱藏在代碼中。點擊保存按鈕會將面板設置爲可見狀態,然後重新載入頁面,此時會調用setTimeout()函數...因此,基本上,您可以單擊保存,然後查看帶有「Details Saved」的面板三秒鐘,此時消失。asp.net外部JavaScript文件未找到Control.ClientID

問題是外部JavaScript文件找不到_pDivAlert.ClientID(我調試過了,它返回null)。它僅在代碼位於.aspx頁面中的標記中時才起作用。有關如何將客戶端ID傳遞給HideControl()函數或從外部JS文件中找到ClientID的建議?

這是我的代碼,有什麼建議嗎?

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

<body onload="ToggleAlert()"> 
<form id="form1" runat="server"> 
<script type="text/javascript"> 
    //alert the user that the details were saved 
    function HideControl() { 
     var control = document.getElementById('<%=_pDivAlert.ClientID %>'); 
     if(control != null) 
      control.style.display = 'none'; 
    } 
    function ToggleAlert() { 
     setTimeout("HideControl()", 3000); 
    } 
</script> 

我也試過ToggleAlert()調用內發送客戶端ID,但沒有奏效:

<body onload="ToggleAlert('<%=_pDivAlert.ClientID %>')"> 

外部JS:

function HideControl(_c) { 
var control = _c; 
if (control != null) 
    control.style.display = 'none'; 
} 
function ToggleAlert(_c) { 
    setTimeout("HideControl(_c)", 3000); 
} 

回答

1

你能展現與面板標記和隱藏它的代碼隱藏?

Visible屬性設置爲false並將樣式display屬性設置爲none - 第一個根本不會呈現該元素,這意味着沒有任何與您正在查找的id一起呈現的內容。

編輯:這可能是因爲您在timeout中調用HideControl的方式 - 這應該是一個函數而不是字符串。

嘗試做

function ToggleAlert(_c) { 
    setTimeout( 
     function() { 
      HideControl(_c); 
     }, 3000); 
} 

只是爲了清楚起見,當你通過一個字符串setTimeout,它的評估,然後運行。 eval生成的代碼塊將運行在與您的ToggleAlert方法不同的範圍內,因此當時_c將不可用。

編輯:您還需要實際獲得對控件的引用。您將id字符串傳遞給ToggleAlert,該字符串將其傳遞給HideControl,該字符串期望對象不是字符串。

function HideControl(_c) { // _c is the id of the element 
    var control = document.getElementById(_c); 
    if (control != null) 
     control.style.display = 'none'; 
} 
+0

感謝您的回覆。我製作了一個HideControl()函數,現在我在外部JS中看到了控件ID。但是現在在調試時,我發現「control.style.display ='none'」中的「style」是「未定義的」。 – Barryman9000 2010-06-25 20:38:35

+0

我編輯我的帖子,以解決您的評論中的問題。 – lincolnk 2010-06-25 21:46:07

+0

不錯!這樣做了,謝謝! – Barryman9000 2010-06-25 22:01:01