Javascript执行功能取决于两个按钮

时间:2016-01-07 11:26:18

标签: javascript jquery

我需要像if / else函数那样根据按钮的组合执行。

我知道它必须像:

if "button1" is active/clicked {
  if "button2" is clicked{
    do sth.}
  else if "button3" is clicked{
    do sth. else}
}

单击第二个按钮时应执行该功能。 我找不到那个

的参考

2 个答案:

答案 0 :(得分:0)

使用变量来识别是否已单击按钮...



var button1 = false;
var button2 = false;

var button_action = function(btn) {
  var msg = document.getElementById('button_message');
  if (btn.value == 'button1') {
    button1 = true;
  } else if (btn.value == 'button2') {
    button2 = true;
  }
  if (button1 && button2) {
    msg.innerHTML = 'Both buttons have been clicked';
  }
}

<form name="buttons" id="buttons">
  <input type="button" value="button1" onclick="button_action(this);">
  <input type="button" value="button2" onclick="button_action(this);">
</form>

<h1 id="button_message">No buttons have been clicked</h1>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

为此,请执行以下操作:

  1. 创建一个变量,告诉您点击了哪个按钮
  2. click事件添加到按钮
  3. 添加条件
  4. Fiddle

    段:

    function addEvent(el, name, func, bool) {
    	if (el.addEventListener)
    		el.addEventListener(name, func, bool);
    	else if (el.attachEvent)
    		el.attachEvent('on' + name, func);
    	else
    		el['on' + name] = func;
    }
    var clicked = {
    	button1: false,
    	button2: false,
    	button3: false
    };
    
    function eventFunc(e) {
    	var t = e.target;
    	if (t.hasAttribute('id') && clicked.hasOwnProperty(t.id))
    		clicked[t.id] = true;
    	
    	if (clicked['button1']) {
    		if (clicked['button2'])
    			alert('button1 and button2 clicked!');
    		else if (clicked['button3'])
    			alert('button1 and button3 clicked!');
    	}
    }
    
    addEvent(button1, 'click', eventFunc, false);
    addEvent(button2, 'click', eventFunc, false);
    addEvent(button3, 'click', eventFunc, false);
    	
    <input type="button" value="button1" id="button1">
    <input type="button" value="button2" id="button2">
    <input type="button" value="button3" id="button3">

    希望有所帮助:)