切换事件监听器

时间:2016-06-11 15:49:52

标签: javascript function javascript-events scope event-listener

我正在尝试创建一个允许我切换元素的eventListener的函数。

在下面的示例中,我有三个按钮: 即可。当我点击 on 按钮时, 按钮即可生效。点击 关闭 按钮后, 按钮不再有效(但现在仍然可以)。< / p>

现在,我可以通过第二次单击 按钮来实现所需的行为,但我想这是一个糟糕的巧合,它不应该以这种方式工作。< / p>

也许我应该补充一点,我想在没有使用jQuery或类似功能的情况下解决这个问题,它需要成为一个函数,因为我会将它用于很多按钮。

(我怀疑带有范围的东西会导致问题( clickHandler ,当调用激活的功能时,该按钮与 clickHandler 不同当调用函数禁用按钮时),但我想不出一种方法来测试它。)

<button type="button" id="mainButton">mainButton
</button>
<button type="button" id="onButton">onButton
</button>
<button type="button" id="offButton">offButton
</button>
<p>mainButton: toggles background color on click
</p>
<p>onButton: turns on mainButtons's functionality</p>
<p>offButton: supposed to turn off mainButton's functionality</p>
let
idle :: Prozess
idle = Prozess{pid=1, arrival=5, computing=10}

1 个答案:

答案 0 :(得分:1)

var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButon = document.querySelector("#offButton");

var element; // declare the element here and change it from toggleButtons when needed.

function clickHandler() {
    document.querySelector(element).classList.toggle('yellow');
}
function activateButton(button) { // You missed this part
    button.addEventListener('click', clickHandler);
}
function disableButton(button) { // You missed this part
    button.removeEventListener('click', clickHandler);
}

function toggleButtons(value, button) {    
    if (value === 1) {
        activateButton(button);  // You missed this part
    } else {
        disableButton(button);  // You missed this part
    }
};

onButton.addEventListener('click', function() {
    element = 'body'; // you can change it to some other element 
    toggleButtons(1, mainButton);
});
offButton.addEventListener('click', function() {
    element = 'body'; // you can change it to some other element 
    toggleButtons(0, mainButton);
});