JQuery :not() 选择器

定义与用法:

:not() 选择器选取除了指定元素以外的所有元素。

最常见的用法:与其他选择器一起使用,选取指定组合中除了指定元素以外的所有元素。

参考代码:

<script>  
    $(function() {  
        $("p:not(#p1)").css("color", "red"); //写法一  
        $("p").not("#p1").css("color", "red"); //写法二  
    })  
</script>  
  
<p id="p1">Hello</p>  
<p id="p2">Hello Again</p>  

执行结果:

HTML DOM reset() 方法或是 <input type="reset"> 元素

参考代码:

<script>  
    $(function() {  
        $("#form1 :input").val("value");  
    })  
</script>  
  
<form id="form1">  
    <input type="text" value="text" />  
    <input type="reset" value="reset" />  
</form>  

点击重置按钮前:

点击重置按钮后:


得出结论:HTML DOM reset() 方法或是 <input type="reset"> 元素的真正作用并不是“清空” <input> 元素中的 value值,而是“重置”还原 <input> 元素中的原本的 value 值。值得注意的是,reset 不能重置按钮类型元素(type=button,reset,submit)的 value 值。

真正清空 form 表单中的内容(JQuery)

参考代码:

<script>  
    $(function() {  
        $("#button").click(function() {  
            $("#form :input").not(":button, :submit, :reset, :hidden").val("").removeAttr("checked").remove("selected");//核心 IE11及以上用这个
    $('form')[0].reset();//IE11以下用这个
        });  
    })  
</script>  
  
<form id="form">  
    <input type="radio" checked="checked" />  
    <input type="checkbox" checked="checked" />  
    <select>  
        <option>option1</option>  
        <option selected="selected">option2</option>  
    </select>  
    <input type="text" value="text" />  
      
    <input type="hidden" value="hidden" />  
    <input type="button" value="button" />  
    <input type="reset" value="reset" />  
    <input type="submit" value="submit" />  
</form>  
  
<button id="button">真正清空</button>  

点击“id=button”的按钮前:

点击"id=button"的按钮后:

 

后续补充:

今天做项目又要清空 form 数据,遇到一个小问题,解决了很久才找到原因,发现上述代码还是有缺陷的。

我在前台需要清空 form value 数据,后台需要取一个 checkbox value 值,如果使用上面的代码就会出现后台取到的 checkbox value 值为空的情况。

所以在这里改进一下上面的代码,做到既能满足前台能移除 checkbox checked 属性,又能保留 checkbox value 值,radio 元素也一样:

$("#form :input").not(":button, :submit, :reset, :hidden, :checkbox, :radio").val("");                      

$("#form :input").removeAttr("checked").remove("selected"); 

 

更多推荐

Jquery清空表单内容