多个内部函数如何根据选泽执行?
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="test">
<span>
<button onclick="test()">按钮</button>
</span>
<span>
<input type="checkbox" name="count" value="jia" />加
<input type="checkbox" name="count" value="jian" />减
<input type="checkbox" name="count" value="cheng" />乘
<input type="checkbox" name="count" value="chu" />除
</span>
</div>
</body>
<script>
function test() {
const count = document.getElementsByName("count");
let fun = countTest();
for (let c of count) {
if (c.value == "jia" && c.checked == true) {
alert("我选择了:" + c.value);
fun();
}
if (c.value == "jian" && c.checked == true) {
alert("我选择了:" + c.value);
}
}
}
function countTest() {
let i = 1;
return function jia() {
let a = i + 1;
console.log(a);
}
// let jia = () => {
// let a = i + 1;
// console.log(a);
// }
return function jian() {
let b = i - 1;
console.log(b);
}
function cheng() {
let c = i * 1;
console.log(c);
}
function chu() {
let d = i / 1;
console.log(d);
}
}
</script>
</html>
如上面例子,我想根据复选框的选择来执行countTest函数里面对应的内部函数,该如何实现?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="test">
<span>
<button onclick="test()">按钮</button>
</span>
<span>
<input type="checkbox" name="count" value="jia" />加
<input type="checkbox" name="count" value="jian" />减
<input type="checkbox" name="count" value="cheng" />乘
<input type="checkbox" name="count" value="chu" />除
</span>
</div>
</body>
<script>
let i = 1;
function jia() {
let a = i + 1;
console.log(a);
}
function jian() {
let b = i - 1;
console.log(b);
}
function cheng() {
let c = i * 1;
console.log(c);
}
function chu() {
let d = i / 1;
console.log(d);
}
function test() {
const count = document.getElementsByName("count");
for (let c of count) {
if ( c.checked == true) {
window()
}
}
}
</script>
</html>
这样可以吗 我好像懂你意思了...你是之前那个用对象封装函数的吗
如果那样的话,那么用没有任何问题!
我之前理解错了 李恒道 发表于 2022-2-20 22:01
我好像懂你意思了...你是之前那个用对象封装函数的吗
如果那样的话,那么用没有任何问题!
我之前理解错了 ...
有闭包的写法吗,我想实现类似与Java类.方法的写法,不暴露 jia jian这些函数 js也有类的:
class Test {
constructor() {
this.i = 1;
}
jia() {
this.i += 1;
console.log(this.i);
}
jian() {
this.i -= 1;
console.log(this.i);
}
//...
}
const countTest = new Test();
countTest.jia(); player 发表于 2022-2-20 22:26
有闭包的写法吗,我想实现类似与Java类.方法的写法,不暴露 jia jian这些函数 ...
用cxxjackie哥哥的类感觉就可以
也可以往函数的property上写一下函数
页:
[1]