Javascript indexOf 不是 return 确切值,有什么解决办法吗?

Javascript indexOf not return exact value, any solution?

请问,如何添加多个查询并return只添加精确值?

    if( placeholder.indexOf('Document') != -1 ){
        $(this).addClass('cpf');
    }
    if( placeholder.indexOf("Document B") != -1 ){
        $(this).addClass('cnpj');
    }
    if( placeholder.indexOf("Document A and B") != -1 ){
        $(this).addClass('cpf_cnpj');
    }

如果我的占位符是 "Document A and B",return 只有 class "cpf_cnpj" 而不是所有 classes.

非常感谢!

你可以试试else...if。此外,您根本不需要 indexOf(),您可以使用严格相等运算符 (===) 或相等运算符 (== 直接检查 placeholder 值).

演示:

$('input').on('focus', function(){
  var placeholder = $(this).attr('placeholder');
  if( placeholder == 'Document'){
    $(this).addClass('cpf');
  }
  else if( placeholder == 'Document B'){
    $(this).addClass('cnpj');
  }
  else if( placeholder == 'Document A and B'){
    $(this).addClass('cpf_cnpj');
  }
});
input{
  display: block;
  margin-bottom: 10px;
}
.cpf { border: 2px solid red }
.cnpj { border: 2px solid green }
.cpf_cnpj { border: 2px solid blue }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input size="1" type="text" name="form_fields[field_1]" id="form-field-field_1" class="elementor-field elementor-size-sm elementor-field-textual" placeholder="Document" maxlength="18">

<input size="1" type="text" name="form_fields[field_1]" id="form-field-field_1" class="elementor-field elementor-size-sm elementor-field-textual" placeholder="Document B" maxlength="18">

<input size="1" type="text" name="form_fields[field_1]" id="form-field-field_1" class="elementor-field elementor-size-sm elementor-field-textual" placeholder="Document A and B" maxlength="18">

尽管我更喜欢使用根本不需要检查的 data-* 属性:

$('input').on('focus', function(){
  var el_class = $(this).data('class');
  $(this).addClass(el_class);
});
input{
  display: block;
  margin-bottom: 10px;
}
.cpf { border: 2px solid red }
.cnpj { border: 2px solid green }
.cpf_cnpj { border: 2px solid blue }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input size="1" type="text" name="form_fields[field_1]" id="form-field-field_1" class="elementor-field elementor-size-sm elementor-field-textual" placeholder="Document" maxlength="18" data-class="cpf">

<input size="1" type="text" name="form_fields[field_1]" id="form-field-field_1" class="elementor-field elementor-size-sm elementor-field-textual" placeholder="Document B" maxlength="18" data-class="cnpj">

<input size="1" type="text" name="form_fields[field_1]" id="form-field-field_1" class="elementor-field elementor-size-sm elementor-field-textual" placeholder="Document A and B" maxlength="18" data-class="cpf_cnpj">

所以从最具体的开始 if/else if

if (placeholder === 'Document A and B') {
  $(this).addClass('cpf_cnpj');
} else if (placeholder.indexOf("Document B") != -1) {
  $(this).addClass('cnpj');
} else { // or else if( placeholder.indexOf('Document') != -1 ){
  $(this).addClass('cpf');
}