【问题标题】:Clear all html controls except some清除除某些之外的所有 html 控件
【发布时间】:2014-08-14 13:15:39
【问题描述】:

我有一个由文本框、文本区域、密码和一些剑道下拉菜单和组合框组成的表单。我想清除Clear按钮单击上的所有控件,除了一个文本框和文本区域。

我已完成以下操作以清除所有控件。

$('#btnClear').on('click', function () {
  $(this).closest('form').find('input[type=text], textarea, input[type=password]').val('');
});

我不知道如何不清除某些控件。

【问题讨论】:

  • 发布您的 html 并指定您不想清除的内容
  • 你试过了吗.not('yadayada
  • 你能发布html吗?
  • $(this).closest('form').find('input[type=text], textarea, input[type=password]').not('<selector>').val('');一样使用.not()

标签: javascript jquery html


【解决方案1】:

使用.not()过滤方法:

说明:从匹配元素集中删除元素。

$('#btnClear').on('click', function () {
    $(this).closest('form')
           .find('input[type=text], textarea, input[type=password]')
           .not('foo')
           .val('');
});

foo 是一个引用异常的选择器(即您不想想要清除的控件)。

【讨论】:

    【解决方案2】:

    您可以通过以下方法实现该功能:

    将一些类应用于您不想清除的控件,如下所示:

    <div id="parent"> 
        <input type="text" id="textOne" /><br/>
        <input type="text" id="textTwo" class="ignoreT" /><br/>
        <textarea id="textThree" class="ignoreTA" ></textarea><br/>
        <input type="text" id="textFour" class="ignoreT" /><br/>
        <button id="clear">Clear</button>
    </div>
    

    现在编写以下代码来清除除忽略类控件之外的所有控件:

    $('#clear').click(function(){
        $(this).closest('form').find('input:not(".ignoreT"), textarea:not("ignoreTA")').val('');
    });
    

    或者您可以将相同的类(假设忽略)应用于所有控件并编写以下代码:

    $('#clear').click(function(){
       $(this).closest('form').find('input, textarea').not('.ignore').val('');
    });
    

    看看它是否适合你。

    【讨论】:

    • 谢谢它对我有用,也谢谢你用适当的例子很好地解释
    【解决方案3】:

    尝试使用:not-selector之类的,

    someId 是一个文本框,otherId 是不应为空的 texxarea

    $('#btnClear').on('click', function () {
        $(this).closest('form').find('input:not(#someId),textarea:not(#otherId)').val('');
    });
    

    您还可以使用non-empty-elements:not 之类的通用类

    $('#btnClear').on('click', function () {
        $(this).closest('form')
               .find('input[type=text], textarea, input[type=password]')
               .not('.non-empty-elements')// filter non-empty-elements
               .val('');
    });
    

    请注意,您需要将non-empty-elements 类添加到那些不应为空的元素中

    【讨论】:

      【解决方案4】:

      使用not()

      $(this).closest('form').find('input[type=text], textarea, input[type=password]').not('#myControlId1,#myControlId2').val('');
      

      其中#myControlId1 & #myControlId1 是您不想清除的控件的 ID

      【讨论】:

        【解决方案5】:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-18
          • 1970-01-01
          • 2018-02-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多