我们需要一个按钮,使用JavaScript切换26个字母的大写和小写,就像android输入法一样。使用两个按钮的代码如下。为了节省空间,我们只给了3个字母按钮。
感谢任何帮助!
<input type="button" id="myBtn_q" onclick="myFunctionTest(this.value)" value="q">
<input type="button" id="myBtn_w" onclick="myFunctionTest(this.value)" value="w">
<input type="button" id="myBtn_e" onclick="myFunctionTest(this.value)" value="e">
<input type="button" id="myBtn_upperCase" onclick="myFunctionupperCase()" value="upperCase">
<input type="button" id="myBtn_lowerCase" onclick="myFunctionlowerCase()" value="lowerCase">
function myFunctionupperCase() {
if(document.getElementById("myBtn_a").value=="a"){
alert(document.getElementById("myBtn_a").value);
var controller=97;
for (controller=97; controller < 123; controller++) {
var id_code="myBtn_"+String.fromCharCode(controller);
//alert(id_code);
document.getElementById(id_code).value=String.fromCharCode(controller-32);
}
}
}
function myFunctionlowerCase() {
if(document.getElementById("myBtn_a").value=="A"){
alert(document.getElementById("myBtn_a").value);
var controller=65;
for (controller=65; controller < 91; controller++) {
var id_code="myBtn_"+String.fromCharCode(controller).toLowerCase();
//alert(id_code);
document.getElementById(id_code).value=String.fromCharCode(controller+32);
}
}
}
我们尝试将两个按钮的代码组合成一个按钮。但是,它没有用。代码如下。
<input type="button" id="myBtn_caseChange" onclick="myFunctioncaseChange()" value="caseChange">
function myFunctioncaseChange() {
if(document.getElementById("myBtn_a").value=="a"){
document.getElementById("myBtn_caseChange").value=="Lower Case"
alert(document.getElementById("myBtn_a").value);
var controller=97;
for (controller=97; controller < 123; controller++) {
var id_code="myBtn_"+String.fromCharCode(controller);
document.getElementById(id_code).value=String.fromCharCode(controller-32);
}
}
if(document.getElementById("myBtn_a").value=="A"){
document.getElementById("myBtn_caseChange").value=="Upper Case"
alert(document.getElementById("myBtn_a").value);
var controller=65;
for (controller=65; controller < 91; controller++) {
var id_code="myBtn_"+String.fromCharCode(controller).toLowerCase();
document.getElementById(id_code).value=String.fromCharCode(controller+32);
}
}
}
答案 0 :(得分:1)
这应该这样做:
(function() { // closure to encapsulate the toggle state
// choose the initial case
var is_upper = true;
// get the toggle button's ID
var toggle = document.getElementById('myBtn_toggle');
// helper function that sets the buttons how you want
function update() {
toggle.value = is_upper ? '\u21E9' : '\u21E7';
for (var c = 1; c <= 26; ++c) {
var lc = String.fromCharCode(96 + c);
var uc = String.fromCharCode(64 + c);
var el = document.getElementById('myBtn_' + lc);
if (!el) continue;
el.value = is_upper ? uc : lc;
}
}
// add an event handler _properly_, without inline handlers
toggle.addEventListener('click', function() {
is_upper = !is_upper; // flip the case
update(); // update the buttons
});
update(); // make sure the page starts how you want
})(); // execute the above closure immediately
演示