代码之家  ›  专栏  ›  技术社区  ›  robjmills

使用prototype检查所有值是否匹配

  •  0
  • robjmills  · 技术社区  · 14 年前

    var val = null;
    var fail = false;
    
    $('form').select('.class').each(function(e){
        if(!val){
            val = $F(e);
        }else{
            if(val != $F(e)) fail = true;
        }
    });
    
    1 回复  |  直到 13 年前
        1
  •  3
  •   npup    14 年前

    哦,这一行应该做到:

    $(form).select('.'+className).invoke('getValue').uniq().size()===1; // true means all values are the same

    • 将(input/etc)元素的值与您要查找的类名(run)组合成一个数组 invoke 在一组选定的元素上)
    • 使数组仅包含唯一值(调用 uniq
    • 看看它的长度是不是1

    原型文档链接: Element.select , Enumerable#invoke , Form.Element.getValue , Array#uniq

    <body>
    
    <form action="#" id="myform">
        <input type="text" name="foo1" class="foo" />
        <input type="text" name="foo2" class="foo" />
        <input type="text" name="foo3" class="foo" />
        <input type="text" name="foo4" class="foo" />
        <input type="text" name="foo5" class="foo" />
        <input type="submit" />
    </form>
    
    <script type="text/javascript">
    // Returns true if all values of elements with a certain classname in the form has the same value
    function bar(form, className) {
        return $(form).select('.'+className).invoke('getValue').uniq().size()===1;
    }
    // Usage: bar('myform', 'foo');
    </script>
    </body>