javascript - 复制 JS 功能在某些文件上无法运行,而在某些文件上完美运行
问题描述
我正在创建一种字典,用户输入一个输入值,不同语言/方式的输出显示在多个不同的字段中。
1 个输入可以有多个输出。输出已针对特定输入存储,因此如果存在特定输入,则显示其指定输出
我正在使用以下代码。
HTML
<div id="input_container">
<input id="input_1" class="text-area-main input_mainn" type="text" placeholder="Input Goes Here" oninput="funcinput1()">
</div>
<div id="output">
<div class="text-detail"><div class="row element-inner single-element"><div class="col-md-11 col-10 position-initial heading-main"><div class="font-style-name"><span>Select My language</span></div></div><div class="col-md-1 col-2 button-main"><button class="ml-auto btn copy-btn btn_cpy col-md-1 col-12 button_copy integration-checklist__copy-button btn_copy" id="btn_copy" data-clipboard-text="" data-clipboard-action="copy" data-clipboard-target="#output_1" >COPY</button></div><div class="col-md-12 col-12 position-initial text-area-outer"><div class="font-pre col-md-12 col-12 signature text-area-inner"><textarea id="output_1" class="text-area-main"></textarea></div></div></div></div>
<div class="text-detail"><div class="row element-inner single-element"><div class="col-md-11 col-10 position-initial heading-main"><div class="font-style-name"><span>Copy Eragon Ancient Language</span></div></div><div class="col-md-1 col-2 button-main"><button class="ml-auto btn copy-btn btn_cpy col-md-1 col-12 button_copy integration-checklist__copy-button btn_copy" id="btn_copy" data-clipboard-text="" data-clipboard-action="copy" data-clipboard-target="#output_2" >COPY</button></div><div class="col-md-12 col-12 position-initial text-area-outer"><div class="font-pre col-md-12 col-12 signature text-area-inner"><textarea id="output_2" class="text-area-main"></textarea></div></div></div></div>
<div class="text-detail"><div class="row element-inner single-element"><div class="col-md-11 col-10 position-initial heading-main"><div class="font-style-name"><span>Pick Older Futhark Runes</span></div></div><div class="col-md-1 col-2 button-main"><button class="ml-auto btn copy-btn btn_cpy col-md-1 col-12 button_copy integration-checklist__copy-button btn_copy" id="btn_copy" data-clipboard-text="" data-clipboard-action="copy" data-clipboard-target="#output_3" >COPY</button></div><div class="col-md-12 col-12 position-initial text-area-outer"><div class="font-pre col-md-12 col-12 signature text-area-inner"><textarea id="output_3" class="text-area-main"></textarea></div></div></div></div>
</div>
JS:
const translator = {
"output_1": {
"speak":"speek","basic":"howtobasic","ok":"k","okay":"k","yay":"yeay","yes":"yass","yeah":"yaaa","alright":"alite","owo":"ewe i nowe yoo did zat","boat":"yes a bowt","uwu":"why yoo kepe doin zat >w>","fuck":"heyy zat badd","there":"der","l":"w","enough":"enof","Z":"zed","ah":"ahe","spam":"spem","is":"iz","giant":"gient","if":"iv","you":"yoo","eat":"eet","too":"to","to":"too","much":"mach","very":"veri","fat":"fats","the":"da","coconut":"kokonut","nut":"nuut","I":"i","back":"bak","she":"se","he":"heee","hello":"henlo","one":"on","been":"bean","lick":"leek","bean":"been","la":"le","that":"zat","language":"langage","jacob":"how u gues ma neam","z":"zzz oh yoo werre takilng","yeea boiiiiiii":"yayeet boi",
},
"output_2":{
"may the stars watch over you":"atra du evar\u00ednya ono varda","may good fortune rule over you":"atra estern\u00ed ono thelduin","may luck and happiness follow you, and may you be shielded from misfortune":"atra guli\u00e4 un ilian tauthr ono un atra ono wa\u00edse sk\u00f6liro fra rauthr","a":"a\u00ed","a deadly poison":"skilna bragh","a melancholy dream of great beauty":"alal\u00eba","a type of vine":"lian\u00ed","air":"vindr","all":"allr","am":"eddyr","an":"a\u00ed","and":"un","apple":"hald","are":"eru","arm":"vaupna","armor":"hernskja","arrow":"oro","as":"nen","ask":"bidja","awaken":"vakna","awry":"vrangr","back (adj)":"aptr","back (n)":"hrygr","back (n)":"bak","bad":"illr",
},
"output_3":{
"speak":"speek","basic":"howtobasic","ok":"k","okay":"k","yay":"yeay","yes":"yass","yeah":"yaaa","alright":"alite","owo":"ewe i nowe yoo did zat","boat":"yes a bowt","uwu":"why yoo kepe doin zat >w>","fuck":"heyy zat badd","there":"der","l":"w","enough":"enof","Z":"zed","ah":"ahe","spam":"spem","is":"iz","giant":"gient","if":"iv","you":"yoo","eat":"eet","too":"to","to":"too","much":"mach","very":"veri","fat":"fats","the":"da","coconut":"kokonut","nut":"nuut","I":"i","back":"bak","she":"se","he":"heee","hello":"henlo","one":"on","been":"bean","lick":"leek","bean":"been","la":"le","that":"zat","language":"langage","jacob":"how u gues ma neam","z":"zzz oh yoo werre takilng","yeea boiiiiiii":"yayeet boi",
}
};
document.querySelector("#input_1").addEventListener("input", (e) => {
for (const output of Object.keys(translator)) {
document.querySelector(`#${output}`).value = translate(e.target, output);
}
});
function translate(input, outputSelector) {
const text = input.value;
const currentTranslator = translator[outputSelector];
const translated = replaceOnceUsingDictionary(currentTranslator, text, function(key, dictionary) {
return dictionary[key];
});
return translated;
}
/*
* @description Replaces phrases in a string, based on keys in a given dictionary.
* Each key is used only once, and the replacements are case-insensitive
* @param Object dictionary {key: phrase, ...}
* @param String content
* @param Function replacehandler
* @returns Modified string
*/
function replaceOnceUsingDictionary(dictionary, content, replacehandler) {
if (typeof replacehandler != "function") {
// Default replacehandler function.
replacehandler = function(key, dictionary) {
return dictionary[key];
}
}
var patterns = [], // \b is used to mark boundaries "foo" doesn't match food
patternHash = {},
oldkey, key, index = 0,
output = [];
for (key in dictionary) {
// Case-insensitivity:
// key = (oldkey = key).toLowerCase();
key = (oldkey = key);
dictionary[key] = dictionary[oldkey];
// Sanitize the key, and push it in the list
patterns.push('\\b(?:' + key.replace(/([[^$.|?*+(){}])/g, '\\$1') + ')\\b');
// Add entry to hash variable, for an optimized backtracking at the next loop
patternHash[key] = index++;
}
var pattern = new RegExp(patterns.join('|'), 'gi'),
lastIndex = 0;
// We should actually test using !== null, but for foolproofness,
// we also reject empty strings
while (key = pattern.exec(content)) {
// Case-insensitivity
// key = key[0].toLowerCase();
key = key[0];
// Add to output buffer
output.push(content.substring(lastIndex, pattern.lastIndex - key.length));
// The next line is the actual replacement method
output.push(replacehandler(key, dictionary));
// Update lastIndex variable
lastIndex = pattern.lastIndex;
// Don't match again by removing the matched word, create new pattern
patterns[patternHash[key]] = '^';
pattern = new RegExp(patterns.join('|'), 'gi');
// IMPORTANT: Update lastIndex property. Otherwise, enjoy an infinite loop
pattern.lastIndex = lastIndex;
}
output.push(content.substring(lastIndex, content.length));
return output.join('');
};
//translator code ends here
var clipboard = new Clipboard('.copy-btn');
clipboard.on('success',function(e){setTooltip(e.trigger,'Copied!')});
function setTooltip(btn,message)
{
$("button.ml-auto.copy-btn.btn_cpy").html('COPY');
$(btn).html('Copied!')
}
如果您查看我的代码,每个输出 textarea 字段都有一个与之关联的复制按钮,该按钮应该复制该字段的值,但在这种情况下它不起作用。该代码在某些页面中停止工作,而在其他页面中工作。(这里的工作代码:https ://thefontworld.com/genz-talk-translator )
两个页面都有相同的 JS 代码和 HTML 代码,只是在“输出”中输入/输出值不同。
我将此代码用于复制功能:
var clipboard = new Clipboard('.copy-btn');
clipboard.on('success',function(e){setTooltip(e.trigger,'Copied!')});
function setTooltip(btn,message)
{
$("button.ml-auto.copy-btn.btn_cpy").html('COPY');
$(btn).html('Copied!')
}
我使用相同的复制功能面临的另一件事是,当它工作时,它只能在新页面加载时工作,但是,一旦我重新加载页面,复制功能就不起作用。
我还是 JS 的新手,所以学习一切,所以任何帮助找到这个复制按钮不起作用的原因都会非常有用。
PS 输入和输出值是在页面中预定义的,可以有 unicode、特殊字符和字母数字值
谢谢!
希望高手给个解决方案!
解决方案
此复制功能应该可以工作:
const button = document.getElementById("button"),
container = document.getElementById("container");
container.addEventListener("click", event => {
const id = event.target.id;
const textarea = document.getElementById("textarea" + id[id.length - 1]);
//just for display
textarea.select();
//copy text
navigator.clipboard.writeText(textarea.value).then(() => {
//text was copied successfully
});
});
<div id="container">
<textarea id="textarea1">some text</textarea>
<button id="button1">copy</button>
<textarea id="textarea2">some text</textarea>
<button id="button2">copy</button>
<textarea id="textarea3">some text</textarea>
<button id="button3">copy</button>
<textarea id="textarea4">some text</textarea>
<button id="button4">copy</button>
</div>
推荐阅读
- xml - 如何更改其中一个属性的值?
- node.js - nodejs中swagger-jsdoc设置的语法错误
- python - python ProcessPoolExecutor在函数中不起作用
- c# - 两个日期之间的计数(C#,CultureInfo)
- pandas - 在熊猫数据框中的一组内除以最大值
- sql-server - 子字符串在我的所有情况下都不起作用,我该如何解决?
- angular - 从 json 加载远程数据
- ionic-framework - 无法通过 JSON 检索 WP 帖子功能图像 url
- mongodb - $gt 内的三元运算符
- javascript - 如何在 LIVE-SERVER 上使用 Javascript 找到当前的 html 文件页名称