如何对来自javascript消息的文本进行硬编码

How to hard code text which are coming from javascript messages

本文关键字:文本 编码 消息 javascript      更新时间:2023-09-26

我们的应用程序已经国际化,并被更改为不同的语言。因此,我们必须对所有消息进行硬编码。我们如何用javascript为消息做到这一点?

这就是我们在html消息中的做法。

<span th:text="#{listTable.deletedFromTable}">deleted</span>     

我们如何为javascript消息硬编码。(更新表格)

$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');

您需要从一开始就将消息放入DOM中,但不显示它们。将这些文本放在span标签中,每个标签都有一个唯一的idth: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));