如何在jQuery中选择输入类型文本和搜索body blur

How to select input types text and search on body blur in jQuery?

本文关键字:文本 搜索 body blur 类型 输入 jQuery 选择      更新时间:2023-09-26

下面的代码段运行良好:

$(function(){
    //trim all input-text fields and remove extra spaces
    $('body').on('blur',':text',function(){
        var newVal=$(this).val().trim();
        $(this).val( newVal.replace( /'s+/g, ' ' ) );
    });
});

问题是,我也需要选择搜索输入字段,我已经尝试了以下没有成功:

':text,:search'

没有像:search这样的选择器,所以您可以使用属性选择器 [type=search] 来代替

$(function(){
    //trim all input-text fields and remove extra spaces
    $('body').on('blur','[type=search],:text',function(){
        var newVal=$(this).val().trim();
        $(this).val( newVal.replace( /'s+/g, ' ' ) );
    });
 });

有效的选择器:https://api.jquery.com/category/selectors/