【问题标题】:Shorter way to check that value of multiple input is empty for jquery检查 jquery 的多个输入的值是否为空的更短方法
【发布时间】:2019-05-03 13:12:51
【问题描述】:
let a = $('#plustitle').val().trim();  // input type text
let b = $('#plustags').val().trim(); // input type text
let c = $('#plustory').val().trim(); // textarea

我需要检查以上变量是否为空,即是否有值“”;

使用 jquery each 循环 - 代码很多。

有没有办法以更短的方式做到这一点。

【问题讨论】:

  • 抱歉,你让我对自己的逻辑感到不安全,但这是正确的^^ !a || !b!(a && b) 相同,因此 if(!(a && b && c))
  • @Andreas,我明白了,请给出答案,我认为没有更短的方法

标签: javascript jquery html html-input


【解决方案1】:

如果我们使用空字符串为falsy这一事实,我们可以满足您的要求

if (!(a && b && c)) {
  // one of them is empty
} 

【讨论】:

    【解决方案2】:

    考虑到正在使用“let”,我假设你有 ES6 支持。 将这些值推送到数组后,您可以使用以下代码:

       let a = $('#plustitle').val().trim();  // input type text
       let b = $('#plustags').val().trim(); // input type text
       let c = $('#plustory').val().trim(); // textarea 
       let someValues = [a, b, c]; // if separate variables are not required, directly push to array   
       someValues.forEach(x =>{ if(!x) {
           //do operation when empty
       }});
    

    【讨论】:

    • if ([a, b, c].some(x => !x)) {...}
    • OP 不想像提到的那样使用循环
    【解决方案3】:

    加入所有变量并检查结果的长度

    let a = $('#plustitle').val().trim();
    let b = $('#plustags').val().trim();
    let c = $('#plustory').val().trim(); 
    
    if ((a+b+c).length == 0)
      console.log("empty");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="plustitle" value="">
    <input type="text" id="plustags" value="">
    <input type="text" id="plustory" value="">

    您还可以简化代码并使用一个选择器

    var values = $('#plustitle, #plustags, #plustory').map(
      (i, ele) => ele.value.trim()
    ).toArray().join('');
    
    if (values.length == 0)
      console.log("empty");
    

    var values = $('#plustitle, #plustags, #plustory').map(
      (i, ele) => ele.value.trim()
    ).toArray().join('');
    
    if (values.length == 0)
      console.log("empty");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="plustitle" value="">
    <input type="text" id="plustags" value="">
    <input type="text" id="plustory" value="">

    【讨论】:

    • “您也可以简化代码” - 仅当 puerto 不需要这些值时。否则你将不得不从 DOM 中获取它们两次
    【解决方案4】:

    您可以通过以下方式对其进行抽象:

    function isEmpty(id) {
      return ($('#' + id).val().trim() == '');
    }
    
    if(!isEmpty('plusTitle') && !isEmpty('plustags') && !isEmpty('plustory')) {
      console.log('none is empty');
    }
    

    【讨论】:

    • 不使用比较运算符
    猜你喜欢
    • 1970-01-01
    • 2019-10-11
    • 2010-12-23
    • 1970-01-01
    • 2011-05-13
    • 2018-03-31
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多