首页 > 解决方案 > 用于 intlTelInput 的 jquery 无法添加事件侦听器

问题描述

尝试做一些类似于国家代码侦听器下拉但使用应该填充国家代码的文本框(以便我随后可以在 PHP 代码中使用该值)。

添加事件侦听器不起作用:

<script>

$(document).ready(function(){

    $("#mobile").intlTelInput({
			onlyCountries: ["au","ca","us","nz","gb"],
    	utilsScript: "<?php echo get_template_directory_uri(); ?>/intl-tel-input/build/js/utils.js",
    	geoIpLookup: function(callback) {
		  	$.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
		    	var countryCode = (resp && resp.country) ? resp.country : "";
		    	callback(countryCode);
		  	});
		},
    	initialCountry: "auto"
    }).addEventListener('countrychange', function() {
			$("#country_code").value = "changed"
		});;

    $('#verify').attr('disabled','disabled');
    $("#mobile").on('input', function() {
    	if ($("#mobile").intlTelInput("isValidNumber")) {
			$('#verify').removeAttr('disabled');
			$("#country_code").innerHTML = "changed"
    	} else {
    		$('#verify').attr('disabled','disabled');
    	}

    });

    $("#register-form").submit(function() {
		$("#mobile").val($("#mobile").intlTelInput("getNumber"));

	});
});
</script>

标签: javascriptjqueryintl-tel-input

解决方案


也许,你问这个问题已经几个月了,下面是解决方案。

你误解了addEventListener. 这可以是任何其他 Javascript 框架的功能。但不是 jQuery 的。

初始化后将以下代码用作脚本。你可以做你想做的事情,countryData.dialCode它会给你国家代码。

jQuery("#mobile").on('countrychange', function(e, countryData){
    console.log(countryData.dialCode);
})

countryData以下是返回的样本intlTelInput

{ areaCodes: null, dialCode: "44", iso2: "gb", name: "United Kingdom", priority: 0 }

我的工作版本是(这是基于 Intelinput 的 jQuery 库版本)

var mobile_with_country_code = '<?php echo $mobile_with_country_code; ?>';
        
        var mobile_number_input = document.querySelector("#mobile");

        mobile_number = window.intlTelInput(mobile_number_input, {
            initialCountry: "ae",
            separateDialCode: true,
            preferredCountries: ["ae","bh","kw","om","qa","sa"],
        });

        if(mobile_with_country_code != ''){
            mobile_number.setNumber(mobile_with_country_code);
        }

        jQuery('#country_code').val(mobile_number.getSelectedCountryData().dialCode);

        mobile_number_input.addEventListener("countrychange", function() {
          jQuery('#country_code').val(mobile_number.getSelectedCountryData().dialCode);
        });

推荐阅读