2

所以我有这个音译功能,如果选中复选框,我需要执行它。问题是,在取消选中复选框后,该功能继续运行。

const checkBox = document.querySelector("#checkbox");
const input = document.querySelector("#input");

function transRussian(){
  ch = ch.replace(/l/g, "л");
  ch = ch.replace(/p/g, "п");
  return ch;
}

checkBox.addEventListener('change',()=>{
  if(checkBox.checked){
    transliterate();
  }
  else{
    console.log("transliteration is turned off")
  }
});

input.addEventListener('keyup',()=>{
  var ch = input.value;
  transRussian(ch);
  input.value = ch;
});
<input type="checkbox" id="checkbox">
<input type="text" id="input">

4

1 回答 1

1

在这个解决方案中,如果checkbox点击翻译,translateBlock()则调用该方法并<textarea>根据逻辑更改元素内的文本。

/* A let variable is declared, not a const, to change the content. */
let checkBox = document.getElementById('checkbox');
let input = document.getElementById('input');

function transRussian(ch){
  ch = ch.replace(/l/g, "л");
  ch = ch.replace(/p/g, "п");
  return ch;
}

function translateBlock(){
  var ch = input.value;
  input.value = transRussian(ch);
}

/* When the checkbox is clicked, the control variable is set to true. */
input.addEventListener('keyup', () => {
  if(checkBox.checked)
    translateBlock();
});

/* This method is triggered when data is entered in the <textarea> element. */
checkBox.addEventListener('change', () => {
  if(checkBox.checked)
    translateBlock();
  else
    console.log("transliteration is turned off")
});
textarea{
  display: block;
}
<span>Translate</span>
<input type="checkbox" id="checkbox"/>

<textarea id="input" name="w3review" rows="4" cols="50">
At w3schools.com you will learn how to make a website. They offer free tutorials in all web development technologies.
</textarea>

于 2022-01-14T05:26:03.947 回答