您需要从一开始就将消息放入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));