首页 > 解决方案 > 使用带有 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>

标签: javascripthtml

解决方案


这是因为您添加的事件侦听器中有错误:

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>


推荐阅读