如何对来自 javascript 条消息的文本进行硬编码
How to hard code text which are coming from javascript messages
我们的应用程序已国际化并更改为不同的语言。出于这个原因,我们必须对所有消息进行硬编码。我们如何为 javascript 中的消息执行此操作?
这就是我们在 html 条消息中的做法。
<span th:text="#{listTable.deletedFromTable}">deleted</span>
我们如何对 javascript 消息进行硬编码。(更新 table)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');
您需要从一开始就将消息放在 DOM
中,但不显示它们。将这些文本放在 span
标签中,每个标签都有一个独特的 id
和 th:text
属性——您可以将它们添加到文档的末尾:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
这将确保您的国际化模块也会在此元素上发挥其魔力,并且即使未显示文本也会进行翻译。
然后在您想要使用该警报的那一刻,获取该隐藏文本并将其注入您需要的位置:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
你问的是这个的另一个变体,你目前有:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
然后您可以将此内容再次添加为未显示的内容 span
,并使用计数占位符:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
您应该确保您的翻译也使用占位符。
然后如下使用,将运行时的占位符替换为:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
您可以创建一个函数来处理此类占位符的替换:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
然后两个例子写成如下:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));
我们的应用程序已国际化并更改为不同的语言。出于这个原因,我们必须对所有消息进行硬编码。我们如何为 javascript 中的消息执行此操作?
这就是我们在 html 条消息中的做法。
<span th:text="#{listTable.deletedFromTable}">deleted</span>
我们如何对 javascript 消息进行硬编码。(更新 table)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');
您需要从一开始就将消息放在 DOM
中,但不显示它们。将这些文本放在 span
标签中,每个标签都有一个独特的 id
和 th:text
属性——您可以将它们添加到文档的末尾:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
这将确保您的国际化模块也会在此元素上发挥其魔力,并且即使未显示文本也会进行翻译。
然后在您想要使用该警报的那一刻,获取该隐藏文本并将其注入您需要的位置:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
你问的是这个的另一个变体,你目前有:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
然后您可以将此内容再次添加为未显示的内容 span
,并使用计数占位符:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
您应该确保您的翻译也使用占位符。 然后如下使用,将运行时的占位符替换为:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
您可以创建一个函数来处理此类占位符的替换:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
然后两个例子写成如下:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));