如何使用复选框启用/禁用 javascript 函数?



Hello stackoverflow,

我将如何(暂时(禁用/启用带有复选框的 javascript 函数。

我希望能够选中一个框,只启用一个或两个函数(包括myScrambleFunction和myConvertFunction(,myConvertFunction将每个奇数字母大写,myScrambleFunction将每个单词打乱一点。有时我只想使用加扰函数(没有大写函数(,反之亦然。

任何建议和示例将不胜感激:)

这:https://jsfiddle.net/MysteriousDuck/3pndLbgq/3/就是我现在所拥有的。

我尝试在谷歌上搜索这个问题,但找不到适合我需求的解决方案。

function myConvertFunction() {
var x = document.getElementById("inputText").value;
var letters = x.split("");
var string = "";
for (i = 0; i < letters.length; i++) {
if (i % 2 == 0) {
string += letters[i].toUpperCase();
} else {
string += letters[i];
}
}
document.getElementById("converted").value = myScrambleFunction(string);
}
function myCopyFunction() {
var copyText = document.getElementById("converted");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
eraseText();
}
function eraseText() {
document.getElementById("converted").value = "";
document.getElementById("inputText").value = "";
document.getElementById("inputText").focus();
}
function myScrambleFunction(text) {
let words = text.split(" ");
words = words.map(word => {
if (word.length >= 3) {
return word.split('').sort(() => 0.7 - Math.random()).join('');
}
return word;
});
return words.join(' ');
}
<body>
<div class="container">
<h1> Text Changer </h1>
<h2> CAPS + randomize letters text changer</h2>
<div class="checkbox">
<input type="checkbox" id="checkbox_1">
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2">
<label for="checkbox_2">Scramble</label>
</div> 
<textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" onclick="myConvertFunction(); myScrambleFunction(text);">Convert</button>
<textarea type="text" placeholder="CoNvErTeD tExT" id="converted" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" onclick="myCopyFunction(); eraseText();">Copy</button>
</div>
</body>

您需要创建另一个函数来检查复选框状态:

var button1Handler = function(e) {
var checked1 = document.getElementById("checkbox_1").checked,
checked2 = document.getElementById("checkbox_2").checked;
if (checked1) myConvertFunction(); 
if (checked2) myScrambleFunction(text);
}

最新更新