【问题标题】:jQuery SerializeArray and Not selectorjQuery SerializeArray 和 Not 选择器
【发布时间】:2016-04-21 12:29:06
【问题描述】:

我正在使用 .serializeArray 函数来收集表单的所有输入,但我想排除某个 div 类中的输入。我认为 .not() 选择器会这样做,但它似乎不起作用。

在最基本的层面上是我的代码:

HTML:

<form class="theForm">
  <input name="a" value="a"/>
  <div class="excludeMe">
    <input name="c" value="c"/>
  </div>
</form>

Javascript:

$.each($(".theForm").not(".excludeMe").serializeArray(), 
function() {
    alert(this.name);
});

我希望警报只是“a”,但这是警报“a”然后是“b”。

小提琴:https://jsfiddle.net/cysaczu5/

【问题讨论】:

    标签: javascript jquery serializearray


    【解决方案1】:

    您必须将所有输入包装在&lt;div&gt;&lt;input/&gt;&lt;/div&gt;

    然后把选择器改成这个$.each($(".theForm :not(.excludeMe) input")

    https://jsfiddle.net/cysaczu5/3/

    我建议删除 div 并将“excludeMe”类直接添加到输入中。然后选择器变成$.each($(".theForm input:not(.excludeMe)")

    【讨论】:

    • 这行得通 - 谢谢。我尝试了 :not() 解决方案,但在 .theForm 之后没有放置空格
    【解决方案2】:

    在输入而不是 div 上使用这个类,它会起作用。

    '
    
    
     $.each($("input").not(".excludeMe").serializeArray(), 
       function() {
        alert(this.name);
    });
    

    '

    <input name="c" class='excludeMe' value="c"/>
    

    JSFidle

    【讨论】:

    • 我已经尝试过将“excludeMe”类移到输入上,但它也不起作用。
    • 查看 JSFiddle 中的示例,它工作正常 :) 此外,您应该循环所有输入而不是类选择器。
    【解决方案3】:

    请尝试

    <form class="theForm">
    <input name="a" value="a"/>
    <div class="excludeMe">
      <input class="excludeMe" name="c" value="c"/>
    </div>
    </form>
    $.each($(".theForm :not(.excludeMe)").serializeArray(), 
    function() {
        alert(this.name);
    });
    

    【讨论】:

    • 您的代码和 OP 的代码没有区别。您应该在 :not 之前添加 input 以使其正常工作
    • 你需要在 :not as @lipp 建议的后面添加输入
    • @MateiMihai - 我在输入中添加了class="excludeMe" 有一个区别。由于"not(.excludeMe)" 将排除具有"excludeMe" 类的表单项,因此我已将其添加到输入中。 "input after the :not" 也不是强制性的。查看JSfiddle
    【解决方案4】:

    最简单的答案是从您要跳过的输入中删除name 属性。这样serializeArray()也跳过了:

    HTML:

    <form class="theForm">
      <input name="a" value="a" />
      <input value="c" />
    </form>
    

    JS:

    $.each($(".theForm").serializeArray(), function() {
        alert(this.name);
    });
    

    【讨论】:

      【解决方案5】:

      只需将input 放在:not 语句之前即可仅匹配表单内的输入,而不匹配表单本身:

      $.each($(".theForm input:not(.excludeMe)").serializeArray(), function() {
          alert(this.name);
      });
      

      https://jsfiddle.net/cysaczu5/5/

      【讨论】:

        猜你喜欢
        • 2016-09-05
        • 1970-01-01
        • 1970-01-01
        • 2011-10-31
        • 2013-05-14
        • 2012-09-17
        • 1970-01-01
        • 1970-01-01
        • 2016-12-19
        相关资源
        最近更新 更多