【问题标题】:Cannot show option selected with templateResult select2无法显示使用 templateResult select2 选择的选项
【发布时间】:2018-01-26 19:52:03
【问题描述】:
function formatCountry(country) {

    if (!country.id) {
        return country.text;
    }
    var $country = $(
        '<span class="flag-icon flag-icon-' + country.id.toLowerCase() + ' flag-icon-squared"></span>' +
        '<span class="flag-text">' + country.text + "</span>"
    );
    return $country;
};

$("[name='country']").select2({

    templateResult: formatCountry,
    data: isoCountries
});

我使用此代码进行国家/地区选择,但是当我刷新页面时,选择的选项返回默认值。

【问题讨论】:

  • 将您选择的值设置为本地存储,并在页面刷新时从本地存储中获取值并设置为下拉。
  • 我已经尝试按照您的方式进行操作,但是它仍然在选项中返回默认值。这是我的 html:
  • 你需要在 document.ready 上设置你的值。或者让我检查你的工作。
  • fiddle 我遵循这段代码,并插入 js : $(function() { if (localStorage.getItem('language')) { $("#language option").eq( localStorage.getItem('language')).prop('selected', true); } $("#language").on('change', function() { localStorage.setItem('language', $('option :selected', this).index()); }); });但它仍然返回默认值

标签: javascript jquery css drop-down-menu


【解决方案1】:

你可以像这样使用本地存储。

$("[name='country']").select2({
  placeholder: "Select a country",
  templateResult: formatCountry,
  data: isoCountries
});
var OldValue = localStorage.getItem("Key");
if (OldValue !== "" && OldValue !== null) {
  $('select').select2({
    placeholder: "Select a country",
    templateResult: formatCountry,
    data: isoCountries
  }).select2('val', OldValue);
}
$("[name='country']").on("change", function() {
  var selected = $(this).val();
  localStorage.setItem("Key", selected);
});

Working Fiddle

运行 fiddle multi-pal time 就可以看到结果了。

【讨论】:

  • 但是作为您的代码,国家的图标标志将消失。我试过了,还是不行。
  • 如果它解决了您的问题,请接受并投票赞成。快乐编码:)
猜你喜欢
  • 1970-01-01
  • 2019-04-19
  • 2020-07-19
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 2015-10-15
相关资源
最近更新 更多