2010-04-05 74 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

相关问题