javascript - 用于 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>
解决方案
也许,你问这个问题已经几个月了,下面是解决方案。
你误解了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);
});
推荐阅读
- php - 如何在 PHP 中随机选择和删除数组中的名称?
- regex - 正则表达式:匹配 domain.com 和 domain.com 的任何子域?
- amazon-web-services - 使用 CloudMan 为 AWS 创建基因组学虚拟实验室 (GVL) 时,用户无权执行 iam:GetRole 错误
- c++ - 在 linux globaly 中存储应用程序序列的正确位置,在初始启动时生成
- excel - 根据单元格的颜色删除行
- c++ - 如何:C++ 读取文件并使用“if 语句”
- android - KOTLIN:android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图
- python - Python click 和 --help 选项回调并不急于
- cakephp - 如何从 CakePHP 3 的结果集中删除一个项目?
- python - 使用 with open 对 json 文件进行编码