javascript - 使用带有 HTML 按钮的开关
问题描述
我想通过使用 HTML 按钮来使用 switch。我有3
按钮,目前只尝试使用第一个按钮。我给了它id=1
,一旦单击它应该将值传递给将使用2
的函数,但是,一旦加载页面,函数就会执行:switchProduct()
case:2
console.log('Apples are $0.32 a pound.') -
好的,所以我什至没有按下按钮,并且一旦加载页面,它就会传递值来切换,当我按下按钮时它根本不起作用(它不再是控制台日志记录),它只是一次运行功能 - 如何要解决这个问题?我想使用按钮多少次。
脚本.js
let bttn = document.getElementById("1");
bttn.addEventListener("click", switchProduct(2));
function switchProduct(x)
{
switch (x)
{
case 1:
console.log('Oranges are $0.59 a pound.');
break;
case 2:
console.log('Apples are $0.32 a pound.');
break;
case 3:
console.log('Bananas are $0.48 a pound.');
break;
case 'Cherries':
console.log('Cherries are $3.00 a pound.');
break;
default:
console.log('Sorry, we are out of ');
}
}
索引.html
<button id="1" class="inline-block typeU">1</button>
解决方案
这是因为您添加的事件侦听器中有错误:
bttn.addEventListener("click", switchProduct(2));
这会将作为事件侦听器的结果添加到按钮的事件中。switchProduct(2)
click
相反,您需要使用匿名函数来包装对switchProduct(2)
:
bttn.addEventListener("click", function() { switchProduct(2); });
请参阅此工作片段中的此处:
let bttn = document.getElementById("1");
bttn.addEventListener("click", function() { switchProduct(2); });
function switchProduct(x){
switch (x) {
case 1:
console.log('Oranges are $0.59 a pound.');
break;
case 2:
console.log('Apples are $0.32 a pound.');
break;
case 3:
console.log('Bananas are $0.48 a pound.');
break;
case 'Cherries':
console.log('Cherries are $3.00 a pound.');
break;
default:
console.log('Sorry, we are out of ');
}
}
<button id="1" class="inline-block typeU">1</button>
推荐阅读
- python - 使用 selenium 抓取超时异常错误
- node.js - 如何使用 node.js 解决方案解析多个 set-cookies?
- css - 更改烧瓶中动态内容的备用链接的字体颜色
- javascript - express.static() 的 Express 中间件没有正确路由并且抛出 next() 不是一个函数
- c# - 将角度乘以小数时统一旋转搞砸了
- excel - 如何改进删除第一个空白行以下的行的代码
- react-native - 反应原生 fetch 钩子并刷新 jwt 令牌
- c - Linux 进程功能为空,尽管可执行文件已设置
- express - 自动将 express.js 服务器部署到 GCE pm2
- sql-server - 不需要密码时设置连接字符串(Windows 授权)