Android开发错误:Error:” ” is not translated in “en” (English) [MissingTranslation]如何处理?

本文介绍如何在Android开发中解决资源文件的翻译问题。包括禁用特定警告、指定默认语言及利用Gradle配置实现全局忽略等方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、尝试添加translatable=”[true / false]”

 <string name="meishop" translatable="false">美购</string> 

2、在resources中添加属性

<resources
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="MissingTranslation">

3、指定语言

  <resources 
        xmlns:tools="http://schemas.android.com/tools"
        tools:locale="en" >
  </resources>

4、使用Android studio可以在build.gradle中的android中添加lintOptions

 lintOptions {
        disable 'MissingTranslation'
    }

或者

lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
<!DOCTYPE html> <html> <head> <title></title> <meta charset="UTF-8"> <link href="../css/bootstrap.min.css" rel="stylesheet" /> <link href="../css/datatables.min.css" rel="stylesheet" /> <link href="../css/jquery.datetimepicker.css" rel="stylesheet" /> <script type="text/javascript" src="../js/date.format.js"></script> <script src="../js/jquery.min.js"></script> <script type="text/javascript" src="../js/jquery.datetimepicker.full.js"></script> <script src="../js/jquery.form.min.js"></script> <script src="../js/bootstrap.bundle.min.js"></script> <script src="../js/datatables.min.js"></script> <script type="text/javascript" src="../js/buttons.html5.min.js"></script> <script src="../js/datav.min.vue.js"></script> <style> .search-span { background-color: LightSteelBlue; } .row-div-20 { margin: 20px; } .row-div-10 { margin: 10px; } .row-div-5 { margin: 5px; } .custom-tooltip { --bs-tooltip-bg: var(--bs-secondary); } </style> </head> <body> <!-- search form --> <form id="search_form" action="../Controller/getTraceabilityList.ashx" method="post" enctype="application/x-www-form-urlencoded" onsubmit="loadDataTable();return false;"> <div class="row row-div-20"> <div class="col-3"> <div class="row"> <div class="col-12"> <div class="input-group"> <span class="input-group-text search-span">生產單號</span> <input id="base-id" name="base-id" type="text" class="form-control" /> </div> </div> <div class="col-12"> <div class="input-group"> <span class="input-group-text search-span">出貨單號</span> <input type="text" class="form-control" disabled /> </div> </div> <div class="col-12"> <div class="input-group"> <span class="input-group-text search-span">日期</span> <input id="start-time" name="start-time" type="text" class="form-control" autocomplete="off" /> <input id="end-time" name="end-time" type="text" class="form-control" autocomplete="off" /> </div> </div> </div> </div> <div class="col-1"> </div> <div class="col-8"> <div class="row"> <div class="col-12"> <div class="input-group"> <span class="input-group-text search-span">料號</span> <input id="parn-no" name="parn-no" type="text" class="form-control" /><!--required--> <span class="input-group-text search-span">批號</span> <input name="batch-no" type="text" class="form-control" /> <span class="input-group-text search-span">DC</span> <input name="dc" type="text" class="form-control" /> <span class="input-group-text search-span">版本</span> <input name="version" type="text" class="form-control" /> </div> </div> <div class="col-10"> <div class="input-group"> <span class="input-group-text search-span">客戶料號</span> <input type="text" class="form-control" disabled /> <span class="input-group-text search-span">客戶批號</span> <input type="text" class="form-control" disabled /> <span class="input-group-text search-span">機臺編號</span> <input name="machine-no" type="text" class="form-control" /> </div> </div> <div class="col-12"> <div class="input-group"> <span class="input-group-text search-span">站別</span> <input id="station" name="station" type="text" readonly class="form-control" autocomplete="off" /> <button type="button" onclick="showStationModal()" class="btn btn-outline-primary"> 選擇站別</button> <span class="input-group-text search-span">WPNL 號</span> <input name="wpnl-no" type="text" class="form-control" disabled /> <span class="input-group-text search-span">SPNL 號</span> <input name="spnl-no" type="text" class="form-control" disabled /> <span class="input-group-text search-span">PCS 號</span> <input name="pcs-no" type="text" class="form-control" disabled /> </div> </div> <div class="col-8"> <div class="input-group"> <span class="input-group-text search-span">Bacode</span> <input id="Code-no" name="Code-no" type="text" class="form-control" /> <button id="search-btn" class="btn btn-primary">查詢</button> </div> </div> </div> </div> </div> <div class="row row-div-10"> <div class="col-11"> <input id="reject" name="checkColumn" type="checkbox" title="test" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" /> <label for="reject" class="btn btn-outline-success" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-custom-class="custom-tooltip" data-bs-title="AOI / OS / VI"> 不良率</label> <input name="reject" type="text" value="N" style="display: none" /> <input id="scrap" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" /> <label for="scrap" class="btn btn-outline-success" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-custom-class="custom-tooltip" data-bs-title="AOI / OS / VI"> 報廢率</label> <input name="scrap" type="text" value="N" style="display: none" /> <input id="ipqc" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="ipqc" class="btn btn-outline-success"> IPQC</label> <input name="ipqc" type="text" value="N" style="display: none" /> <input id="oqc" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" /> <label for="oqc" class="btn btn-outline-success"> OQC 批退率</label> <input name="oqc" type="text" value="N" style="display: none" /> <input id="mrb" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" /> <label for="mrb" class="btn btn-outline-success"> MRB 報廢率</label> <input name="mrb" type="text" value="N" style="display: none" /> </div> </div> <div class="row row-div-10"> <div class="col-12"> <input id="materiel" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="materiel" class="btn btn-outline-success">原物料異常</label> <input name="materiel" type="text" value="N" style="display: none" /> <input id="eim" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" /> <label for="eim" class="btn btn-outline-success">設備 A 級告警數</label> <input name="eim" type="text" value="N" style="display: none" /> <input id="mes" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" /> <label for="mes" class="btn btn-outline-success">MES 設備維修記錄</label> <input name="mes" type="text" value="N" style="display: none" /> <input id="potion-oos" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="potion-oos" class="btn btn-outline-success">藥水 OOS 異常點數</label> <input name="potion-oos" type="text" value="N" style="display: none" /> <input id="potion-ooc" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="potion-ooc" class="btn btn-outline-success">藥水 OOC 異常點數</label> <input name="potion-ooc" type="text" value="N" style="display: none" /> <input id="product-oos" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="product-oos" class="btn btn-outline-success">產品 OOS 異常點數</label> <input name="product-oos" type="text" value="N" style="display: none" /> <input id="product-ooc" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="product-ooc" class="btn btn-outline-success">產品 OOC 異常點數</label> <input name="product-ooc" type="text" value="N" style="display: none" /> <input id="great-exception" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" /> <label for="great-exception" class="btn btn-outline-success">重大異常</label> <input name="great-exception" type="text" value="N" style="display: none" /> <input id="rework" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="rework" class="btn btn-outline-success">重工</label> <input name="rework" type="text" value="N" style="display: none" /> <input id="exception-handle" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="exception-handle" class="btn btn-outline-success">異常處置</label> <input name="exception-handle" type="text" value="N" style="display: none" /> <input id="complaint" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" disabled /> <label for="complaint" class="btn btn-outline-success">客訴</label> <input name="complaint" type="text" value="N" style="display: none" /> </div> </div> <div class="row row-div-10"> <div class="col-12"> <input id="only-exception" name="checkColumn" type="checkbox" class="btn-check" onchange="checkboxChange($(this))" autocomplete="off" /> <label for="only-exception" class="btn btn-outline-success">只看異常</label> <input name="only-exception" type="text" value="N" style="display: none" /> <input id="all" type="checkbox" class="btn-check" onchange="changeAll($(this))" autocomplete="off" /> <label for="all" class="btn btn-outline-success">ALL</label> <input name="type" type="text" value="list" style="display: none" /> <input id="isSearching" type="text" value="N" style="display: none" /> <button id="submit-btn" type="submit" class="btn btn-primary">查詢</button> </div> </div> </form> <!-- datatable --> <div class="row row-div-20"> <div class="table-responsive col-lg-12"> <table id="table_id" class="display nowrap table table-primary table-striped table-hover text-center align-middle"> <thead> <tr id="table_head_id"> </tr> </thead> <tbody id="tbody_id"> </tbody> </table> </div> </div> <!-- Station Modal --> <div id="station-modal" class="modal fade" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> 站別選擇</h5> </div> <div class="modal-body"> <div class="row"> <div class="col-4"> <input type="text" placeholder="站別名稱" onkeyup="screenStation($(this))" class="form-control" /> </div> </div> <br /> <div id="station-div" class="row"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> 關閉</button> <button type="button" onclick="clearStation()" class="btn btn-danger"> 清除</button> <button type="button" onclick="confirmStation()" class="btn btn-primary" data-bs-dismiss="modal"> 確認</button> </div> </div> </div> </div> <!-- Info Modal --> <div id="info-modal" class="modal fade" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header"> <h5 id="modal-head-id" class="modal-title"> </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button> </div> <div id="modal-content-id" class="modal-body"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> Close</button> </div> </div> </div> </div> <script type="text/javascript"> var table; const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]'); const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl)); $(function () { //得到当前时间 var now = new Date(); var endDate = now.format('Y-m-d H:i'); now.setTime(now.getTime() - 60 * 60 * 1000); var startDate = now.format("Y-m-d H:i"); $('#start-time').datetimepicker({ format: 'Y-m-d H:i', step: 1, value: startDate }); $('#end-time').datetimepicker({ format: 'Y-m-d H:i', step: 1, value: endDate }); $.datetimepicker.setLocale('zh'); initStation(); //给行绑定选中事件 $('#table_id tbody').on('click', 'tr', function () { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { $('#table_id tbody > tr').removeClass('selected'); $(this).addClass('selected'); } }); }); function initStation() { $.ajax({ url: '../Controller/getTraceabilityList.ashx', data: { 'type': 'station' }, success: function(result) { $.each(result.data.list, function(i, n) { $('#station-div').append( '<div class="col-2">' + '<div class="form-check">' + '<input id="' + n + '" value="' + n + '" type="checkbox" class="btn-check" />' + '<label for="' + n + '" class="btn btn-outline-success btn-sm">' + n + '</label>' + '</div>' + '</div>' ); }); } }); } // code輸入後查詢 function getSampleBoardData() { var data; var codeNo = document.getElementById("Code-no").value; $.ajax({ url: '../Controller/getTraceabilityList.ashx?type=codeNo', data: { 'codeNo': codeNo }, async: false, success: function (result) { data = result; } }); return data; }; document.getElementById("search-btn").addEventListener("click", function() { var codeNo = document.getElementById("Code-no").value; var date = getSampleBoardData() document.getElementsByName('base-id')[0].value = date.list; document.getElementsByName('batch-no')[0].value = date.list1; document.getElementsByName('parn-no')[0].value = date.list2; // error: function() { // alert(‘查询失败,请重试’); // } }); function showStationModal() { clearStation(); var stationStr = $('#station').val(); var stationArr if (stationStr != '') { stationArr = stationStr.split(','); } $.each(stationArr, function(i, n) { $(eval(n)).prop('checked', true); }); var stationModal = new bootstrap.Modal($("#station-modal")); stationModal.show(); } function screenStation(input) { var str = input.val().toUpperCase(); $('#station-div > div').hide(); if (str == "") { $('#station-div > div').show(); } else { $('[id*="' + str + '"]').parent().parent().show(); } } function clearStation() { $('#station-div input').prop('checked', false); } function confirmStation() { var str = ""; $('#station-div input:checked').each(function (i, e) { str += ($(e).attr('id') + ','); }); $('#station').val(str.substring(0, str.length - 1)); } function checkboxChange(checkbox) { $('[name="' + checkbox.attr('id') + '"]').val(checkbox.prop('checked') ? 'Y' : 'N'); } function changeAll(checkbox) { var checkboxes = $('[name="checkColumn"]'); if (checkbox.prop('checked')) { checkboxes.prop('checked', true); } else { checkboxes.prop('checked', false); } checkboxes.each(function (i, e) { checkboxChange($(e)); }); } function loadDataTable() { if ($('#isSearching').val() === 'Y') { alert('系統查詢中,請稍等···'); return; } $('#isSearching').val('Y'); if (!$('#reject').prop('checked') && !$('#scrap').prop('checked') && !$('#oqc').prop('checked') && !$('#mrb').prop('checked') && !$('#eim').prop('checked') && !$('#mes').prop('checked') && !$('#great-exception').prop('checked') && $('#only-exception').prop('checked')) { $('#isSearching').val('N'); alert('未選擇異常項,無法只看異常。'); return; } let startTime = Date.parse($('#start-time').val()); let endTime = Date.parse($('#end-time').val()); let diffMin = Math.floor((endTime - startTime) / 60000); if (diffMin > 3 * 24 * 60) { $('#isSearching').val('N'); alert('只能查询三天内数据。'); return; } if ($('#base-id').val() == '' && $('#parn-no').val() == '' && ($('#reject').prop('checked') || $('#scrap').prop('checked') || $('#oqc').prop('checked') || $('#mrb').prop('checked') || $('#eim').prop('checked') || $('#mes').prop('checked') || $('#great-exception').prop('checked'))) { $('#isSearching').val('N'); alert('查询额外字段,请添加生产单号或批号条件进行筛选。') return; } $('#submit-btn').append(' <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>'); $('#search_form').ajaxSubmit({ success: function (result) { if (table != null) { table.destroy(); } $('#table_head_id').empty(); $('#tbody_id').empty(); $.each(result.data.head, function (i, n) { $('#table_head_id').append('<th class="text-center">' + n + '</th>'); }); table = $('#table_id').DataTable({ data: result.data.list, fixedHeader: true, autoWidth: false, scrollX: true, scrollY: 700, searching: 5000, destroy: true, deferRender: true, //延遲渲染 lengthMenu: [ [25, 50, -1], [25, 50, 'All'] ], dom: "<'row'<'col-sm-12 col-md-2'B><'col-sm-12 col-md-1'l><'col-sm-12 col-md-9'f>>" + "<'row'<'col-sm-12'tr>>" + "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>", buttons: ['copy', 'excel'], ordering: false }); $('#submit-btn').text('查詢'); $('#isSearching').val('N'); } }); } function showEIM(count, partId, lotId, machineNo, inDate, outDate) { if (count <= 0) { shwoInfoModal('設備 A 級告警明細', '該機臺告警數為 0'); return; } $.ajax({ async: false, url: '../Controller/getTraceabilityList.ashx', data: { 'type': 'eim', 'partId': partId, 'lotId': lotId, 'machineNo': machineNo, 'inDate': inDate, 'outDate': outDate }, success: function (result) { var content = '<table class="table table-warning table-striped table-hover text-nowrap">' + '<thead><tr>' + '<th>設備名稱</th>' + '<th>告警編碼</th>' + '<th>告警信息</th>' + '<th>時間</th>' + '</tr></thead>' + '<tbody id="tbody_id">' $.each(result.data.list, function (i, n) { content += '<tr>' + '<td>' + n.eqName + '</td>' + '<td>' + n.eventCode + '</td>' + '<td>' + n.eventMessage + '</td>' + '<td>' + n.insertTime + '</td>' + '</tr>' }); content += '</tbody></table>' shwoInfoModal('設備 A 級告警明細', content); } }); } function showMES(count, machineNo, inDate, outDate) { if (count <= 0) { shwoInfoModal('MES 設備維修記錄', '該機臺維修記錄為 0。'); return; } $.ajax({ async: false, url: '../Controller/getTraceabilityList.ashx', data: { 'type': 'mes', 'machineNo': machineNo, 'inDate': inDate, 'outDate': outDate }, success: function (result) { var content = '<table class="table table-warning table-striped table-hover text-nowrap">' + '<thead><tr>' + '<th>設備名稱</th>' + '<th>記錄 1</th>' + '<th>記錄 2</th>' + '<th>記錄 3</th>' + '<th>記錄 4</th>' + '<th>記錄 5</th>' + '<th>申請時間</th>' + '<th>維修開始時間</th>' + '<th>維修結束時間</th>' + '</tr></thead>' + '<tbody id="tbody_id">' $.each(result.data.list, function (i, n) { content += '<tr>' + '<td>' + n.deptName + '</td>' + '<td>' + n.notepad1 + '</td>' + '<td>' + n.notepad4 + '</td>' + '<td>' + n.notepad5 + '</td>' + '<td>' + n.notepad6 + '</td>' + '<td>' + n.notepad7 + '</td>' + '<td>' + n.entDate + '</td>' + '<td>' + n.startRepairDate + '</td>' + '<td>' + n.endRepairDate + '</td>' + '</tr>' }); content += '</tbody></table>' shwoInfoModal('設備 A 級告警明細', content); } }); }; function shwoInfoModal(title, content) { $('#modal-head-id').text(title) $('#modal-content-id').empty(); $('#modal-content-id').append(content); var infoModal = new bootstrap.Modal($("#info-modal")); infoModal.show(); } </script> </body> </html> 切换中英文页面
最新发布
08-06
<think>根据提供的HTML代码,我们注意到页面中包含了多个中文字符,并且有一个需求是“切换中英文页面”。因此,我们需要实现一个中英文切换的功能。这通常可以通过以下步骤实现: 1. 准备中英文两套文本资源(资源文件或对象)。 2. 在页面中为需要切换的文本元素设置特定的类名或ID,以便于定位。 3. 编写切换函数,根据当前语言状态,将页面中的文本替换为对应语言的文本。 4. 将当前语言状态保存到cookie或localStorage中,以便在页面刷新后保持语言状态。 由于原页面没有英文版本,我们需要先为每个需要翻译的文本准备英文翻译。我们可以创建一个对象来存储中英文对照的文本。 ### 实现步骤 #### 1. 定义语言资源对象 在JavaScript中定义一个对象,包含页面中所有需要翻译的文本。例如: ```javascript var langResources = { "zh-CN": { "productionOrder": "生產單號", "shipmentOrder": "出貨單號", "date": "日期", "materialNo": "料號", "batchNo": "批號", // ... 其他文本 }, "en-US": { "productionOrder": "Production Order", "shipmentOrder": "Shipment Order", "date": "Date", "materialNo": "Material No", "batchNo": "Batch No", // ... 其他文本 } }; ``` #### 2. 为需要翻译的元素添加标识 在HTML中,为需要翻译的元素添加一个`data-i18n`属性,属性值为资源对象的key。例如: ```html <span class="input-group-text search-span" data-i18n="productionOrder">生產單號</span> ``` #### 3. 编写语言切换函数 编写一个函数,根据选择的语言,遍历所有带有`data-i18n`属性的元素,并替换其文本内容。 #### 4. 保存和读取语言状态 使用localStorage保存用户选择的语言,并在页面加载时应用。 #### 5. 添加语言切换按钮 在页面上添加一个按钮,用于触发语言切换。 ### 代码实现 #### 修改HTML,添加语言切换按钮 在页面的合适位置(例如顶部)添加一个按钮: ```html <button id="langSwitch" class="btn btn-outline-secondary">English</button> ``` #### 定义语言资源 在`<script>`标签中定义语言资源对象: ```javascript // 语言资源 var langResources = { "zh-CN": { "productionOrder": "生產單號", "shipmentOrder": "出貨單號", "date": "日期", "materialNo": "料號", "batchNo": "批號", "dc": "DC", "version": "版本", "customerMaterialNo": "客戶料號", "customerBatchNo": "客戶批號", "machineNo": "機臺編號", "station": "站別", "wpnlNo": "WPNL 號", "spnlNo": "SPNL 號", "pcsNo": "PCS 號", "barcode": "Bacode", "defectRate": "不良率", "scrapRate": "報廢率", "ipqc": "IPQC", "oqcRejectRate": "OQC 批退率", "mrbScrapRate": "MRB 報廢率", "materialException": "原物料異常", "eimAlarm": "設備 A 級告警數", "mesRepair": "MES 設備維修記錄", "potionOOS": "藥水 OOS 異常點數", "potionOOC": "藥水 OOC 異常點數", "productOOS": "產品 OOS 異常點數", "productOOC": "產品 OOC 異常點數", "majorException": "重大異常", "rework": "重工", "exceptionHandle": "異常處置", "complaint": "客訴", "onlyException": "只看異常", "all": "ALL", "query": "查詢", "stationSelection": "站別選擇", "stationName": "站別名稱", "close": "關閉", "clear": "清除", "confirm": "確認", "equipmentAlarmDetails": "設備 A 級告警明細", "mesRepairRecords": "MES 設備維修記錄" }, "en-US": { "productionOrder": "Production Order", "shipmentOrder": "Shipment Order", "date": "Date", "materialNo": "Material No", "batchNo": "Batch No", "dc": "DC", "version": "Version", "customerMaterialNo": "Customer Material No", "customerBatchNo": "Customer Batch No", "machineNo": "Machine No", "station": "Station", "wpnlNo": "WPNL No", "spnlNo": "SPNL No", "pcsNo": "PCS No", "barcode": "Barcode", "defectRate": "Defect Rate", "scrapRate": "Scrap Rate", "ipqc": "IPQC", "oqcRejectRate": "OQC Reject Rate", "mrbScrapRate": "MRB Scrap Rate", "materialException": "Material Exception", "eimAlarm": "Equipment A Alarm Count", "mesRepair": "MES Repair Records", "potionOOS": "Potion OOS Exception Points", "potionOOC": "Potion OOC Exception Points", "productOOS": "Product OOS Exception Points", "productOOC": "Product OOC Exception Points", "majorException": "Major Exception", "rework": "Rework", "exceptionHandle": "Exception Handle", "complaint": "Complaint", "onlyException": "Only Exception", "all": "ALL", "query": "Query", "stationSelection": "Station Selection", "stationName": "Station Name", "close": "Close", "clear": "Clear", "confirm": "Confirm", "equipmentAlarmDetails": "Equipment A Alarm Details", "mesRepairRecords": "MES Repair Records" } }; ``` #### 编写切换语言函数 ```javascript // 当前语言状态,默认为中文 var currentLang = localStorage.getItem('language') || 'zh-CN'; // 切换语言函数 function switchLanguage(lang) { currentLang = lang; localStorage.setItem('language', lang); // 遍历所有带有data-i18n属性的元素 $('[data-i18n]').each(function() { var key = $(this).data('i18n'); $(this).text(langResources[lang][key]); }); // 更新按钮文本 if (lang === 'zh-CN') { $('#langSwitch').text('English'); } else { $('#langSwitch').text('中文'); } } // 页面加载时应用语言 $(document).ready(function() { switchLanguage(currentLang); // 绑定切换按钮事件 $('#langSwitch').click(function() { if (currentLang === 'zh-CN') { switchLanguage('en-US'); } else { switchLanguage('zh-CN'); } }); }); ``` #### 修改HTML元素,添加data-i18n属性 例如: ```html <span class="input-group-text search-span" data-i18n="productionOrder">生產單號</span> <input id="base-id" name="base-id" type="text" class="form-control" placeholder="" data-i18n-placeholder="productionOrder" /> ``` 注意:对于placeholder,我们使用`data-i18n-placeholder`,同样需要在切换语言时更新。 修改切换语言函数以处理placeholder: ```javascript function switchLanguage(lang) { currentLang = lang; localStorage.setItem('language', lang); // 更新文本内容 $('[data-i18n]').each(function() { var key = $(this).data('i18n'); $(this).text(langResources[lang][key]); }); // 更新placeholder $('[data-i18n-placeholder]').each(function() { var key = $(this).data('i18n-placeholder'); $(this).attr('placeholder', langResources[lang][key]); }); // 更新按钮文本 if (lang === 'zh-CN') { $('#langSwitch').text('English'); } else { $('#langSwitch').text('中文'); } } ``` ### 完整代码整合 由于原页面代码较长,这里只展示修改的部分。在`<body>`开始处添加语言切换按钮,并在`<script>`标签中添加上述语言切换代码。 注意:需要为页面中所有需要翻译的文本添加`data-i18n`属性,并为输入框的placeholder添加`data-i18n-placeholder`属性。 ### 示例修改 以生产单号为例: ```html <div class="input-group"> <span class="input-group-text search-span" data-i18n="productionOrder">生產單號</span> <input id="base-id" name="base-id" type="text" class="form-control" data-i18n-placeholder="productionOrder" /> </div> ``` ### 注意事项 1. 语言资源对象需要包含页面中所有需要翻译的文本。 2. 切换语言后,动态生成的内容(如表格头部)可能也需要翻译,需要在生成时调用翻译函数或重新生成。 3. 对于固定文本(如按钮、标签等)通过上述方法处理,对于从服务器返回的数据(如表格内容),通常不需要翻译,因为服务器返回的数据已经是用户需要的语言(或者根据用户语言设置返回相应的数据)。 由于时间限制,这里只实现了静态文本的切换。对于动态生成的文本(例如通过AJAX加载的表格表头),需要在生成时根据当前语言设置文本。 ### 修改动态生成的文本 例如,在`loadDataTable`函数中,表头是动态生成的,我们需要根据当前语言来设置表头文本。我们可以将表头的key也定义在语言资源中,然后根据当前语言获取对应的文本。 在语言资源对象中添加表头文本: ```javascript "zh-CN": { // ... 其他 "header1": "生產單號", "header2": "料號", // ... }, "en-US": { "header1": "Production Order", "header2": "Material No", // ... } ``` 然后在生成表头时: ```javascript $.each(result.data.head, function (i, n) { // 假设n是资源key,如'header1' var translated = langResources[currentLang][n] || n; $('#table_head_id').append('<th class="text-center">' + translated + '</th>'); }); ``` 注意:这需要服务器返回的表头数据是资源key,而不是具体的文本。或者服务器根据当前语言返回对应的文本(通过请求参数传递当前语言)。 ### 总结 我们通过以下步骤实现了中英文切换: 1. 定义语言资源对象。 2. 为静态元素添加翻译标识。 3. 编写切换语言的函数,并保存语言状态。 4. 添加切换按钮。 5. 处理动态内容的翻译。 由于原页面代码较长,需要修改的地方较多,请根据实际情况调整。 §§相关问题§§: 1. 如何实现多语言切换的Vue版本? 2. 如何将语言资源存储在单独的文件中? 3. 如何通过后端实现动态内容的翻译? 4. 如何实现浏览器的语言自动检测?</think>## 解决中英文页面切换问题 根据提供的代码,我发现页面需要实现中英文切换功能。以下是完整的解决方案,包括代码实现和解释: ### 解决方案步骤 1. **创建语言资源文件** 2. **实现语言切换机制** 3. **修改页面元素以支持多语言** 4. **添加语言切换按钮** ### 完整代码实现 #### 1. 在 `<head>` 中添加语言资源文件引用 ```html <!-- 添加语言资源文件 --> <script type="text/javascript" src="../js/lang-resource.js"></script> ``` #### 2. 创建语言资源文件 `lang-resource.js` ```javascript // 语言资源对象 const langResources = { "zh-CN": { "productionOrder": "生產單號", "shipmentOrder": "出貨單號", "date": "日期", "materialNo": "料號", "batchNo": "批號", "dc": "DC", "version": "版本", "customerMaterialNo": "客戶料號", "customerBatchNo": "客戶批號", "machineNo": "機臺編號", "station": "站別", "wpnlNo": "WPNL 號", "spnlNo": "SPNL 號", "pcsNo": "PCS 號", "barcode": "Bacode", "defectRate": "不良率", "scrapRate": "報廢率", "ipqc": "IPQC", "oqcRejectRate": "OQC 批退率", "mrbScrapRate": "MRB 報廢率", "materialException": "原物料異常", "eimAlarm": "設備 A 級告警數", "mesRepair": "MES 設備維修記錄", "potionOOS": "藥水 OOS 異常點數", "potionOOC": "藥水 OOC 異常點數", "productOOS": "產品 OOS 異常點數", "productOOC": "產品 OOC 異常點數", "majorException": "重大異常", "rework": "重工", "exceptionHandle": "異常處置", "complaint": "客訴", "onlyException": "只看異常", "all": "ALL", "query": "查詢", "stationSelection": "站別選擇", "stationName": "站別名稱", "close": "關閉", "clear": "清除", "confirm": "確認", "equipmentAlarmDetails": "設備 A 級告警明細", "mesRepairRecords": "MES 設備維修記錄" }, "en-US": { "productionOrder": "Production Order", "shipmentOrder": "Shipment Order", "date": "Date", "materialNo": "Material No", "batchNo": "Batch No", "dc": "DC", "version": "Version", "customerMaterialNo": "Customer Material No", "customerBatchNo": "Customer Batch No", "machineNo": "Machine No", "station": "Station", "wpnlNo": "WPNL No", "spnlNo": "SPNL No", "pcsNo": "PCS No", "barcode": "Barcode", "defectRate": "Defect Rate", "scrapRate": "Scrap Rate", "ipqc": "IPQC", "oqcRejectRate": "OQC Reject Rate", "mrbScrapRate": "MRB Scrap Rate", "materialException": "Material Exception", "eimAlarm": "Equipment A Alarm Count", "mesRepair": "MES Repair Records", "potionOOS": "Potion OOS Exception Points", "potionOOC": "Potion OOC Exception Points", "productOOS": "Product OOS Exception Points", "productOOC": "Product OOC Exception Points", "majorException": "Major Exception", "rework": "Rework", "exceptionHandle": "Exception Handle", "complaint": "Complaint", "onlyException": "Only Exception", "all": "ALL", "query": "Query", "stationSelection": "Station Selection", "stationName": "Station Name", "close": "Close", "clear": "Clear", "confirm": "Confirm", "equipmentAlarmDetails": "Equipment A Alarm Details", "mesRepairRecords": "MES Repair Records" } }; // 当前语言状态 let currentLang = localStorage.getItem('language') || 'zh-CN'; // 获取翻译 function getTranslation(key) { return langResources[currentLang][key] || key; } ``` #### 3. 修改页面元素以支持多语言 在 HTML 中为需要翻译的元素添加 `data-i18n` 属性: ```html <!-- 示例: --> <span class="input-group-text search-span" data-i18n="productionOrder">生產單號</span> <input id="base-id" name="base-id" type="text" class="form-control" data-i18n-placeholder="productionOrder" /> ``` #### 4. 添加语言切换按钮 在 `<form>` 上方添加语言切换按钮: ```html <div class="row row-div-10 justify-content-end"> <div class="col-auto"> <div class="btn-group" role="group"> <button type="button" class="btn btn-outline-primary active" id="zhBtn">中文</button> <button type="button" class="btn btn-outline-primary" id="enBtn">English</button> </div> </div> </div> ``` #### 5. 实现语言切换功能 在 `<script>` 标签中添加以下代码: ```javascript // 语言切换函数 function switchLanguage(lang) { currentLang = lang; localStorage.setItem('language', lang); // 更新文本内容 $('[data-i18n]').each(function() { var key = $(this).data('i18n'); $(this).text(getTranslation(key)); }); // 更新placeholder $('[data-i18n-placeholder]').each(function() { var key = $(this).data('i18n-placeholder'); $(this).attr('placeholder', getTranslation(key)); }); // 更新按钮文本 $('#submit-btn').text(getTranslation('query')); $('#search-btn').text(getTranslation('query')); // 更新模态框标题 $('#station-modal .modal-title').text(getTranslation('stationSelection')); $('#station-div input').next('label').each(function() { $(this).text($(this).attr('for')); }); } // 页面加载时应用语言 $(function () { // 应用当前语言 switchLanguage(currentLang); // 绑定语言切换按钮 $('#zhBtn').click(function() { switchLanguage('zh-CN'); $(this).addClass('active'); $('#enBtn').removeClass('active'); }); $('#enBtn').click(function() { switchLanguage('en-US'); $(this).addClass('active'); $('#zhBtn').removeClass('active'); }); // 设置初始按钮状态 if (currentLang === 'zh-CN') { $('#zhBtn').addClass('active'); } else { $('#enBtn').addClass('active'); } // ...其他初始化代码... }); ``` #### 6. 处理动态内容的多语言支持 对于动态生成的内容(如表格表头),需要在生成时应用语言设置: ```javascript function loadDataTable() { // ...其他代码... $('#search_form').ajaxSubmit({ success: function (result) { // ...其他代码... // 重建表头 - 应用多语言 $('#table_head_id').empty(); $.each(result.data.head, function (i, n) { // 假设表头键值在资源文件中定义 var translated = getTranslation(n) || n; $('#table_head_id').append('<th class="text-center">' + translated + '</th>'); }); // ...其他代码... } }); } ``` ### 关键实现说明 1. **语言资源管理**: - 使用 `langResources` 对象存储所有语言文本 - 支持中英文两种语言(可扩展更多语言) 2. **语言切换机制**: - 使用 `switchLanguage()` 函数更新界面文本 - 通过 `localStorage` 保存用户选择的语言 - 页面加载时自动应用上次选择的语言 3. **元素标记**: - 使用 `data-i18n` 属性标记需要翻译的文本元素 - 使用 `data-i18n-placeholder` 标记输入框的占位符 4. **动态内容处理**: - 表格表头等动态内容在生成时调用 `getTranslation()` - 模态框内容在显示时应用当前语言 5. **按钮状态管理**: - 使用 Bootstrap 的按钮组实现切换效果 - 当前语言按钮保持激活状态 ### 额外优化建议 1. **服务器端多语言支持**: ```javascript // 在AJAX请求中添加语言参数 $('#search_form').ajaxSubmit({ data: { lang: currentLang }, // ... }); ``` 2. **日期格式化适配**: ```javascript // 在日期选择器中适配语言 $('#start-time').datetimepicker({ format: 'Y-m-d H:i', step: 1, lang: currentLang === 'zh-CN' ? 'zh' : 'en' }); ``` 3. **DataTables 本地化**: ```javascript table = $('#table_id').DataTable({ // ... language: { url: `../js/datatables-${currentLang}.json` } }); ``` 4. **工具提示本地化**: ```javascript // 更新工具提示文本 $('[data-bs-toggle="tooltip"]').each(function() { var key = $(this).data('bs-title'); if (key) { $(this).attr('data-bs-title', getTranslation(key)); } }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值