【问题标题】:JQuery compare arrays for any matchJQuery比较任何匹配的数组
【发布时间】:2013-05-03 21:05:24
【问题描述】:

我认为我遇到了一个非常简单的问题,但我无法解决。

在提交表单时,我想比较两个隐藏输入类型的值,如果找到任何匹配项,则向用户返回警报并阻止提交。几乎隐藏的输入类型值将是 1-3,可能是 1、12、123、13 等。因此,如果是 1 和 123,则发出警报。

所以我尝试过这样的事情,但我显然对自己在做什么感到困惑,呵呵。

 var new_products = $('#new_products');
 var array_new_products = jQuery.makeArray(new_products);
 var existing_products = $('#existing_products');
 var array_existing_products = jQuery.makeArray(existing_products);

 $("#my_form").submit(function(e) {

 if (jQuery.inArray(existing_products, new_products) >= 0) {
            e.preventDefault();
            alert ("This Promotion matches one or more products already associated to this Group.  If you continue the existing Promotion will be cancelled and replaced with the currently selected Promotion!");
 }
 return true;
 });

我愿意通过比较字符串并返回匹配项或其他任何东西来做到这一点。我对 Jquery 还很陌生。提前致谢。

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:
    $.each($('#new_products').val().split(''), function(i, char) {
        var existing = $('#existing_products').val();
    
        if (existing.indexOf(char) != -1)
            alert('mathces found');
    });
    

    检查#new_product返回值中的任何字符是否存在于#existing_products返回值中?

    【讨论】:

    • 你不能在.split()的结果上调用.each()。你的意思是.forEach()?还是您的意思是改用$.each
    • 漂亮,非常感谢。现在像冠军一样工作。从美国东部时间下午 2 点开始,我就一直在搞砸它:(。+1 进行更正哈哈。我想为什么......不会......这......工作?!?!?!
    猜你喜欢
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多