所以我有一个文本框,用户可以写一个URL。
我有一个下拉菜单,上面有各国的国旗和它们的代码。
我想要实现的是,当用户键入URL时,标志将更改为URL的域。示例:如果用户键入google.com,则下拉菜单应选择点后的值,并选择美国标志。
我正在使用这个库:https://github.com/mrmarkfrench/country-select-js
下面是我的HTML代码:
<form method="post">
<input type="hidden" name="addsite" value="true" />
<p>
<label for="site_url">Site url:</label>
<input type="text" name="site_url" id="urlText" placeholder="domain.xxx" value="" />
</p>
<label for="site_url">Search locale:</label>
<input id="country_selector" type="text">
<label for="site_url"></label>
<br>
<br>
<input type="submit" name="submit" class="btn" value="Add">
</form>下面是脚本:
//the script to initalize the dropdown
$("#country_selector").countrySelect({
defaultCountry: "dk",
//onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
preferredCountries: ['dk', 'gb', 'us', 'ca']
});
//script to change the dropdown value
$('#urlText').change(function changeCountry(string selectedCountryValue) {
$("#country_selector").countrySelect("selectCountry", $selectedCountryValue);
});
//script I've attempted to write
(function($) {
$('#urlText').on('change', function() {
var value = this.value,
parts = this.value.split('.'),
str, $opt;
for (var i = 0; i < parts.length; i++) {
str = '.' + parts.slice(i).join('.');
$opt = $('#country_selector selectCountry[value="' + str + '"]');
if ($opt.length) {
$opt.prop('selected', true);
break;
}
}
})
})(jQuery);所以最后两个脚本是有问题的。我如何编写它们,以便changeCountry函数接受一个字符串selectedValue,然后最后一个函数应该调用changeCountry(str)?
编辑:我想我可能犯了基本的jQuery错误……
发布于 2017-02-19 03:20:22
下面是一个如何获取url的域名后缀部分的示例。
$('#btnGetUrlDomain').on('click', function() {
var parts = $('#txtUrl').val().split('.')
var domain = parts[parts.length - 1]
console.log(domain)
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='txtUrl' type='text' value='www.google.com' />
<button id='btnGetUrlDomain'>
Get URL
</button>
因此,您只需调用country-select-js countrySelect方法。
$('#btnGetUrlDomain').on('click', function() {
var parts = $('#txtUrl').val().split('.')
var domain = parts[parts.length - 1]
$("#country_selector").countrySelect("selectCountry", domain);
})发布于 2017-02-19 04:02:01
所以这是我需要的:
$('#urlText').on('change', function() {
var parts = $('#urlText').val().split('.')
var domain = parts[parts.length - 1]
$("#txtUrls").val(domain);
$("#country_selector").countrySelect("selectCountry", domain);
})https://stackoverflow.com/questions/42319305
复制相似问题