代码之家  ›  专栏  ›  技术社区  ›  Francesco G.

jquery获取空输入

  •  2
  • Francesco G.  · 技术社区  · 8 年前

    在jquery 1.8.3之前,我可以使用此代码获取空输入

    $('#loginCard input[value=]').addClass('error');
    

    在jquery 1.8.3之后,此语法不起作用。发生了什么变化?

    我想对jquery 3.2.1做同样的事情,而不使用函数或类似的函数:

    $('#loginCard input').each(function (){ 
        if($(this).val()==""){
           $(this).addClass("error"); 
        }
    });
    

    遵循“少写多做”的理念

    3 回复  |  直到 8 年前
        1
  •  1
  •   Rory McCrossan Hsm Sharique Hasan    8 年前

    事实上,它在没有引用的情况下工作是一个bug/特性,这在1.8.3中甚至不应该被允许。

    加引号,例如。 [value=""] ,它在jquery的任何版本(过去或现在)中都可以正常工作:

    $('#loginCard input[value=""]').addClass('error');
    .error { border: 1px solid #C00; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="loginCard">
      <input type="text" value="" />
    </div>

    如果需要属性选择器的替代方法,可以使用 filter() 这样地:

    $('#loginCard input').filter(function() {
      return $(this).val().trim() == '';
    }).addClass('error');
    
        2
  •  0
  •   Md. Abu Sayed    8 年前

    你的代码工作在钢这个版本,我希望你的另一个问题影响这个部分。您也可以在此处尝试此代码 https://jsfiddle.net/tzk4a593/ 或者遵循这个准则

    jQuery("#loginCard").find('input').each(function (){ 
        if($(this).val()==""){
           $(this).addClass("error"); 
        }
    });
    input.error { border: 1px solid red; }
    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>
      
    <form id="loginCard" action="#">
      <input type="text" value="" name="one" />
       <input type="text" value="xxxxxx" name="some" />
      <input type="text" value="" name="two" />
      <input type="text" value="myVal" name="three" />
    </form>
        3
  •  0
  •   MattDiMu    8 年前

    即使使用引号也有效,使用 $item.val() 使用css选择器并不相同,因为后者不尊重用户输入。因此,css选择器解决方案将始终显示错误,即使输入不再为空:

    https://codepen.io/MattDiMu/pen/aKzbgw

    推荐文章