所以我试图做一个简单的翻译器。我只是有一些问题。例如,我希望它注册字母B,然后它会写bob。现在,当我在“转换为”框(这是普通变量)中写b时,它在“转换为”框(即theifTalk)[object HTMLTextAreaElement] bob中说。并在控制台中说:无法读取未定义的属性“重复”。无论如何,这是我的代码:

const theifTalk = document.getElementById('theiftalk');
const normal = document.getElementById('normal');
const translateBtn = document.getElementById('translateBtn');


translateBtn.onclick = function() {
    theifTalk.value = "";
    translate();
}

function translate() {

    if (normal.value.includes("b")) {
        var bCount = normal.value.match(/b/g)||[].length;

        b().repeat(bCount.length);
    }

}

function b() {
    theifTalk.value = theifTalk + "bob";
}


HTML代码:

<textarea type="text" id="normal" rows="15" cols="80" placeholder="Normal text goes in here..."></textarea>
<textarea type="text" id="theiftalk" rows="15" cols="80" placeholder="Theif Talk text goes out here..."></textarea>
<br>
<button id="translateBtn">translate</button>

最佳答案

由于您没有从函数中返回任何内容,因此明确返回了undefined。您已经从函数返回了值。另外,theifTalk是元素本身,您应该从中获取值:

function b() {
  theifTalk.value = theifTalk.value + "bob";
  return theifTalk.value;
}


您还应该将值设置回theifTalk

theifTalk.value = b().repeat(bCount.length);




const theifTalk = document.getElementById('theiftalk');
const normal = document.getElementById('normal');
const translateBtn = document.getElementById('translateBtn');

translateBtn.onclick = function() {
  translate();
}
function translate() {
  if (normal.value.includes("b")) {
    var bCount = normal.value.match(/b/g)||[].length;
    theifTalk.value = b().repeat(bCount.length);
  }
}

function b() {
  theifTalk.value = theifTalk.value + "bob";
  return theifTalk.value;
}

<textarea type="text" id="normal" rows="15" cols="80" placeholder="Normal text goes in here..."></textarea>
<textarea type="text" id="theiftalk" rows="15" cols="80" placeholder="Theif Talk text goes out here..."></textarea>
<br>
<button id="translateBtn">translate</button>

09-17 09:52