bootstrap-datepicker:如何动态更改语言属性? [英] bootstrap-datepicker : How to change language attribute dynamically?
问题描述
我正在使用来自 https://github.com/uxsolutions/bootstrap-datepicker 的 bootstrap-datepicker一切都按预期进行.
I'm using bootstrap-datepicker from https://github.com/uxsolutions/bootstrap-datepicker and everything works as expected.
我的初始化脚本是
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
language: "en"
});
但是现在我想动态更改语言并且我已经尝试过
But now I want to change the language dynamically and I've tried
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
language: $('.active .lang-id').text().toLowerCase() // <- the field from which I read lang param i.e ru, es, etc...
});
而且它的语言与第一次阅读时的语言不一样.如何使它工作?甚至有可能吗?
And it does not work the language is the same as was first read. How to make it work? Is it even possible?
更新 NO.1
在@Cameron 的帮助下,我成功地使用动态更新了语言这段代码,但现在当我按下日期选择器时,我可以在一瞬间看到日期选择器弹出窗口(显示日历)如何从语言 A 转换到语言 B.如何避免这种令人不快的效果?
with a help of @Cameron I succeeded in updating a language dynamically using this code, but now when I press on a datepicker I can see in a split of a second how the datepicker popup (showing calendar) transitions from a language A to language B. How to avoid this unpleasant effect?
更新的代码
$('.input-group.date').on('click', function() {
if ($(this).datepicker != null) {
console.log("is not null");
$(this).datepicker('destroy');
}
currentLanguage = $('.active .lang-id').text().toLowerCase();
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
language: currentLanguage
});
$(this).datepicker('update');
$(this).datepicker('show');
console.log("test" + $('.active .lang-id').text().toLowerCase());
});
推荐答案
尝试抓取 datepicker() 之前的文本值
Try grabbing the value of the text before the datepicker()
*更新,发现一些setDefaults";在 jquery 日期选择器上
*update, found some "setDefaults" on jquery Datepicker
const language= $('.active .lang-id').text().toLowerCase();
console.log('select language is '+ language);
//be sure your selector is working
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
language: language
});
更新
$( document ).ready(function() {
const language= $('.active .lang-id').text().toLowerCase();
//be sure your selector is working
console.log('select language is '+ language);
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
language: language
});
});
您可能加载了本地脚本
$( document ).ready(function() {
const language= $('.active .lang-id').text().toLowerCase();
//be sure your selector is working
console.log('select language is '+ language);
const script = document.createElement('script');
script.src = `https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/locales/bootstrap-datepicker.${language}.min.js`;
// Append to the `head` element
document.head.appendChild(script);
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
language: language
});
});
这篇关于bootstrap-datepicker:如何动态更改语言属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!