elseif onclick函数不会显示

时间:2019-01-15 13:29:17

标签: javascript html

我正在尝试通过单击按钮来输出答案。问题是,它将仅对if语句(第一个按钮)而不是else ifs(第二个和第三个按钮)执行此操作。我在做什么错了?

<body>
<button id="button1" type="button" name="button">Button 1</button>
<button id="button2" type="button" name="button">Button 2</button>
<button id="button3" type="button" name="button">Button 3</button>


<script type="text/javascript">
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");

function message() {

 if (button1.onclick) {
   console.log("fere");
 }

 else if(button2.onclick) {
   console.log("33.");
 }

 else if (button3.onclick) {
   console.log("hiii");
 }
 }


button1.onclick = message;
button2.onclick = message;
button3.onclick = message;

我希望在每个按钮上单击一次后这些输出:

费 33 hiii

2 个答案:

答案 0 :(得分:2)

尝试在按钮中使用onclick属性(类似于在angular / vue模板中使用的方式)

ERROR TypeError: "_co.p is undefined"   
function message(n) {

     if (n==1) {
         console.log("fere");
     }

     else if(n==2) {
         console.log("33.");
     }

     else if (n==3) {
         console.log("hiii");
     }
 }

答案 1 :(得分:1)

我不确定是否可以检查方法,通常在这种情况下,通常需要根据ID或某些唯一标识符进行验证,请尝试以下实现

const button1 = document.getElementById('button1');
const button2 = document.getElementById('button2');
const button3 = document.getElementById('button3');

function handleButtonClick(event) {
    const target = event.target;
    const id = target.id;

    if (id === 'button1') {
        console.log('fere');

        return;
    }

    if (id === 'button2') {
        console.log('33.');

        return;
    }

    if (id === 'button3') {
        console.log("hiii");

        return;
    }
}

button1.addEventListener('click', handleButtonClick, true);
button2.addEventListener('click', handleButtonClick, true);
button3.addEventListener('click', handleButtonClick, true);
<button id="button1">Button 1</button>
<button id="button2">Button 2</button>
<button id="button3">Button 3</button>