我有一个小项目,其中有一个由 JQuery UI 插件提供的选择下拉菜单。下拉菜单包含国家/地区及其调用代码的列表。有没有一种方法可以在时显示国家/地区名称和调用代码选择处于焦点上,并且当其因选定值而失焦时仅显示调用代码。
这是代码
HTML
<select class="form-control" id="cdropmovil" name="dropmovil"></select>
JavaScript函数
$.getJSON('../../Content/paises.json', function (json) {
var countries = json.countries;
countries.forEach(function (country) {
var opcion = '<option value="'+country.code+'">' + country.name + ' '
+ country.code + '</option>';
$("#cdropmovil").append(opcion);
}, this);
这是我显然不成功的尝试......
$("#cdropmovil").on('change', function () {
$(this).text($("#cdropmovil option:selected").val());
})
最佳答案
您可以使用data-*
属性来存储每个option
标签文本值。这样,如果您在 value
更改时更新 option
标记文本值,您的文本值就不会丢失。
你的$.getJSON(...)
将被修改为
$.getJSON('../../Content/paises.json', function (json) {
var countries = json.countries;
countries.forEach(function (country) {
//updated opcion variable
var opcion = '<option data-country-code-name="'+country.name+' '+country.code+'" value="'+country.code+'">' + country.name + ' '+ country.code + '</option>';
$("#cdropmovil").append(opcion);
}, this);
现在您可以使用 data-*
属性值更改 change()
事件处理程序上的文本
这是修改后的代码
$(document).ready(function(){
$("body").on("focus","select",function(){
$(this).children("option").each(function(){
$(this).text($(this).data("country-code-name"));
});
});
$("body").on("change","select",function(){
var see = $("select option:selected").val();
$("select option:selected").text(see);
//This blur is added to remove focus on value select which was not commented link
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="countries">
<option data-country-code-name="USA 1" value="1">USA 1</option>
<option data-country-code-name="Africa 2" value="2">Africa 2</option>
<option data-country-code-name="Switzerland 3" value="3">Switzerland 3</option>
<option data-country-code-name="Germany 4" value="4">Germany 4</option>
</select>
关于javascript - JQuery UI 选择菜单更改显示更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37249057/