【问题标题】:Need help with inArray在 inArray 方面需要帮助
【发布时间】:2010-07-12 01:53:10
【问题描述】:

嗨,我有以下功能,只有在检查另外两个复选框中时,才需要使其返回false。

$.validator.addMethod(
"ReutersNA",
function(value, element) {
    var selectedCountry = $("#Country").val();
    var NorthAmerica = new Array("USA","CAN","MEX");
    if($.inArray(selectedCountry,NorthAmerica) > -1) {
    return true;
    } else return false;
    }, "Cannot select Reuters News outside of North America."
);

I need to add if($("#IQBAS, #IQPRE").is(":checked") && the above function = return true    

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:

    你的意思是这样的?

    $.validator.addMethod(   
    "ReutersNA",   
    function(value, element) {   
        var selectedCountry = $("#Country").val();   
        var NorthAmerica = new Array("USA","CAN","MEX"); 
         return ($("#IQBAS, #IQPRE").is(":checked") && $.inArray(selectedCountry,NorthAmerica) > -1);
    }, 
    "Cannot select Reuters News outside of North America."   
    );  
    

    【讨论】:

    • @RightSaidFred 如果您不选择#IQBAS 和/或#IQPRE,这仍会返回“Cannot...”。仅当您检查 IQBAS 和/或 IQPRE 时,我才需要它返回消息
    【解决方案2】:

    让我们试着变得有点笼统......

    $.validator.addMethod(   
    "ReutersNA",   
    function(value, element, params) {   
        var selectedCountry = value;   
        var NorthAmerica = new Array("USA","CAN","MEX"); 
         return (params && $.inArray(selectedCountry,NorthAmerica) > -1);
    }, 
    "Cannot select Reuters News outside of North America."   
    );
    

    那么你可以像这样使用它

     rules: {
         Country :  {
             ReutersNA : $("#IQBAS, #IQPRE").is(":checked")
         }
     }
    

    【讨论】:

    • 我看到了它是如何工作的,根据正在检查的参数验证规则......不幸的是,无论检查什么,它都会返回错误
    【解决方案3】:

    你的问题有点不清楚。我认为你的意思是如果它被检查并且元素不在数组中,它应该返回 false(显示消息)。

    $.validator.addMethod(   
    "ReutersNA",   
    function(value, element) {   
        var selectedCountry = $("#Country").val();   
        var NorthAmerica = new Array("USA","CAN","MEX");
        // Valid (true) if neither checked, or element is found in array.  
        return !$("#IQBAS, #IQPRE").is(":checked") || $.inArray(selectedCountry,NorthAmerica) > -1);
    }, 
    "Cannot select Reuters News outside of North America."   
    );  
    

    【讨论】:

    • 我得到这个错误不见了; before 语句 [Break on this error] || $.inArray(selectedCountry,NorthAmerica) > -1);\n
    • @Dirty,将这两个条件放在同一行(我只是调整了答案)。
    猜你喜欢
    • 2011-05-09
    • 2011-01-27
    • 2014-02-06
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多