国际电话输入无法与 jQuery 3.6.0 一起正常工作

intl-tel-input not working properly with jQuery 3.6.0

我有 2 个代码,一个是旧代码,但它运行良好,然后我决定升级到 jquery 3.6.0,但我遇到了代码停止工作的问题,所以我从 here 但它无法正常工作。

旧代码

var telInput = $("#phone"),
  errorMsg = $("#error-msg"),
  validMsg = $("#valid-msg");

// initialise plugin
telInput.intlTelInput({
  utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.4/js/utils.js"
});

var reset = function() {
  telInput.removeClass("error");
  errorMsg.addClass("hide");
  validMsg.addClass("hide");
};

// on blur: validate
telInput.blur(function() {
  reset();
  if ($.trim(telInput.val())) {
    if (telInput.intlTelInput("isValidNumber")) {
      validMsg.removeClass("hide");
      var getCode = telInput.intlTelInput('getSelectedCountryData').dialCode;
      alert(getCode);
    } else {
      telInput.addClass("error");
      errorMsg.removeClass("hide");
    }
  }
});

// on keyup / change flag: reset
telInput.on("keyup change", reset);
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/6.4.1/css/intlTelInput.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/6.4.1/js/intlTelInput.min.js"></script>

<input id="phone" type="tel">
<span id="valid-msg" class="hide">✓ Valid</span>
<span id="error-msg" class="hide">Invalid number</span>

在 jsbin 上:https://jsbin.com/heqokumase/edit?html,js,output

此代码运行良好,例如,它不允许任何输入(数字和 + 除外),如果用户输入数字,它还会自动删除国家代码。

新密码

var input = document.querySelector("#registration-phone-number");
var errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];
window.addEventListener("load", function() {

  errorMsg = document.querySelector("#error-msg"),
    validMsg = document.querySelector("#valid-msg");

  var iti = window.intlTelInput(input, {
    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/utils.js"
  });
  window.intlTelInput(input, {
    // allowDropdown: false,
    // autoHideDialCode: false,
    // autoPlaceholder: "off",
    // dropdownContainer: document.body,
    // excludeCountries: ["us"],
    // formatOnDisplay: false,
    geoIpLookup: function(callback) {
      $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
        var countryCode = (resp && resp.country) ? resp.country : "";
        callback(countryCode);
      });
    },
    hiddenInput: "full_number",
    initialCountry: "auto",

    // localizedCountries: { 'de': 'Deutschland' },
    // nationalMode: false,
    // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
    placeholderNumberType: "MOBILE",
    // preferredCountries: ['cn', 'jp'],
    separateDialCode: true,
    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/utils.js",
  });
  $(validMsg).hide();
  input.addEventListener('blur', function() {
    reset();
    if (input.value.trim()) {
      if (iti.isValidNumber()) {
        $(validMsg).show();
      } else {
        $(input).addClass('form-control-danger');
        var errorCode = iti.getValidationError();
        errorMsg.innerHTML = errorMap[errorCode];

        $(errorMsg).show();
      }
    }
  });
  input.addEventListener('change', reset);
  input.addEventListener('keyup', reset);
});


var reset = function() {
  $(input).removeClass('form-control-danger');
  errorMsg.innerHTML = "";
  $(errorMsg).hide();
  $(validMsg).hide();

};
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/css/intlTelInput.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/intlTelInput.js"></script>
<input id="registration-phone-number" type="tel">
<span id="valid-msg" class="hide">✓ Valid</span>
<span id="error-msg" class="hide">Invalid number</span>

在 jsbin 上:https://jsbin.com/mumedakiku/edit?html,js,output

它可以工作,但它不会将输入限制为仅(数字和 +),它也不会在输入数字时自动删除国家代码,如果您输入数字而不输入国家代码,也会出现错误“太短”,尤其是在加载开始时,它会自动获取用户国家,但正如我所说,如果你写的号码没有国家代码,它会给出错误“太短”,除非你再次 select 国家然后它会给有效。

如何通过jquery的新更新和intl-tel-input的新更新使新代码像旧代码一样完美工作?

我解决了它,这里是任何想要它的人的代码:)

     var input = document.querySelector("#phone"),
        errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"],
        result = document.querySelector("#result");
    
    
    window.addEventListener("load", function () {
      
      
      errorMsg = document.querySelector("#error-msg");
    
    function getIp(callback) {
     fetch('https://ipinfo.io', { headers: { 'Accept': 'application/json' }})
       .then((resp) => resp.json())
       .catch(() => {
         return {
           country: '',
         };
       })
       .then((resp) => callback(resp.country));
    }
      
    var iti = window.intlTelInput(input, {
                // allowDropdown: false,
                // dropdownContainer: document.body,
                // excludeCountries: ["us"],
                hiddenInput: "full_number",                         
                nationalMode: false,
                formatOnDisplay: true,           
                separateDialCode: true,
                autoHideDialCode: true, 
                autoPlaceholder: "aggressive" ,
                initialCountry: "auto",
                placeholderNumberType: "MOBILE",
                preferredCountries: ['il','ge'],           
                geoIpLookup: getIp,
                utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/utils.js",
            });
      
      
      input.addEventListener('keyup', formatIntlTelInput);
    input.addEventListener('change', formatIntlTelInput);
    
    function formatIntlTelInput() {
        if (typeof intlTelInputUtils !== 'undefined') { // utils are lazy loaded, so must check
            var currentText = iti.getNumber(intlTelInputUtils.numberFormat.E164);
            if (typeof currentText === 'string') { // sometimes the currentText is an object :)
                iti.setNumber(currentText); // will autoformat because of formatOnDisplay=true
            }
        }
    }
       
      
             
           input.addEventListener('keyup', function () {     
                reset();
                if (input.value.trim()) {
                    if (iti.isValidNumber()) {
            $(input).addClass('form-control is-valid');
                             
                    } else {                  
                        $(input).addClass('form-control is-invalid');
                        var errorCode = iti.getValidationError();
                        errorMsg.innerHTML = errorMap[errorCode];                   
                        $(errorMsg).show();
                    }
                }
            });        
            input.addEventListener('change', reset);        
            input.addEventListener('keyup', reset);
      
          var reset = function () {
            $(input).removeClass('form-control is-invalid');
            errorMsg.innerHTML = "";
            $(errorMsg).hide();
          
        };
      
      
      
    ////////////// testing - start //////////////
    
    input.addEventListener('keyup', function(e) {
      e.preventDefault();
      var num = iti.getNumber(),
          valid = iti.isValidNumber();
      result.textContent = "Number: " + num + ", valid: " + valid;
    }, false);
    
    input.addEventListener("focus", function() {
      result.textContent = "";
    }, false);
        
      
      $(input).on("focusout", function(e, countryData) {
                   var intlNumber = iti.getNumber();
                   console.log(intlNumber);   
               });
      
    ////////////// testing - end //////////////
      
        });
        
        
      //-----------------------only-phone-number-input code (with +)-------------------------------start-------// 
       function isPhoneNumberKey(evt)
       {
           var charCode = (evt.which) ? evt.which : evt.keyCode
           if (charCode != 43 && charCode > 31 && (charCode < 48 || charCode > 57))
               return false;
           return true;
       }

       //-----------------------only-phone-number-input code (with +)-------------------------------end-------//         
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/css/intlTelInput.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/intlTelInput.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>


<div class="form-group has-danger">
  <input id="phone" class="" type="tel" name="phone" maxlength="15" />
  <br>
  <span id="error-msg" class="hide"></span>

<p id="result"></p> 
  </div>