2010-04-05 17 views
1

我想傳遞給一個JavaScript腳本函數的控件ID的數組,所以它會切換控制的啓用狀態。如何將匿名數組的字符串傳遞給JavaScript函數?

例如,在C#這將是這樣的:

func(false, new[] { "Control1", "Control2", "Control3" }); 

在此功能,我想找到相應的控制和禁用/啓用它們。對於一個控件我下一步做到這一點:

<script type="text/javascript" language="javascript"> 
    function switchControls(value, arr) { 
     for (var n = 0; n < array.length; n++) 
      document.getElementById([n]).disabled = value; 
    } 
</script> 

<asp:CheckBox runat="server" 
    onclick="switchControls(this.checked, 
     [ 
      '<%= Control1.ClientID %>', 
      '<%= Control2.ClientID %>' 
     ])" 
    Text="Take?" /> 

如何正確實現這個?我有使用jQuery嗎?

+1

一個在JS文字數組只是一個逗號分隔的列表'[中,方,括號]'。奇怪的是,在你的'onclick'處理程序代碼中你已經有了一個這樣的例子,所以你已經知道如何去做。您已經向數組中的函數發送了兩個控制ID,而不是一個。那麼問題是什麼? – 2010-04-05 17:56:38

+1

看起來像switchControls內部數組索引中的一個bug。 – ajm 2010-04-05 17:58:57

+0

@ajm:仍然不起作用。 'alert(arr.length)'什麼也不顯示 – abatishchev 2010-04-05 18:01:50

回答

0
<script type="text/javascript" language="javascript"> 
    function toggleControls(value) { 
     $('.toggle').each(function() { 
      if (value) { 
       $(this).removeAttr('disabled'); 

      } 
      else { 
       $(this).attr('disabled', 'true'); 
      } 
     }); 
    } 
</script> 

<asp:CheckBox runat="server" onclick="toggleControls(this.checked)" Text="Take?" /> 
<asp:TextBox runat="server" CssClass="toggle" /> 
2

你不 「都」 使用jQuery,但它somekind的冷卻器使用它:)

function checkme(arr){ 
    if($.isArray(arr)){ 
    $.each(arr, function(){ 
     var currentState = this.attr('disabled'); 
     if(currentState == 'disabled' || currentState == 'true'){ 
      this.removeAttr('disabled');   
     } 
     else{ 
      this.attr('disabled', 'disabled'); 
     } 
    }); 
    } 
} 

用法:checkme([$("#someid"), $("#anotherid"), $("#anotherid")]);

+0

您的代碼需要修改以允許切換以啓用/禁用控件。 – CAbbott 2010-04-05 18:00:17

+0

如何結合ASP.NET調用''<%= code %>''和jQuery調用'$(「code」)'? – abatishchev 2010-04-05 19:25:10

3

沒有的jQuery(或任何其他庫)必要的。

它看起來像你的代碼將這樣的伎倆有修改或兩個:

<script type="text/javascript"> 
    function switchControls(value, arr) { 
     for (var n = 0; n < arr.length; n++){ 
      document.getElementById(arr[n]).disabled = value; 
     } 
    } 
</script> 

只要你的ASP語句將在布爾和一組ID(它看起來像它了,但我不熟悉ASP),它應該工作。例如,您的onClick可以稱之爲switchControls這樣的:

switchControls(true, ['foo','bar','baz']); 
+0

'switchControls(this.checked,[<%= txtMinimalCommission.ClientID%>])'也不'switchControls(this.checked,[txtMinimalCommission.ClientID])'作爲數組傳遞。它不被JS功能識別爲數組 – abatishchev 2010-04-05 18:08:01

+0

clientID不是JavaScript可以識別的有效屬性。您需要將ASP呈現出來,然後將其作爲字符串傳遞給您的數組。像'switchControls(this.checked,[「<%= txtMinimalCommission.ClientID%>」])''''。 – ajm 2010-04-05 19:28:42

相關問題