简体   繁体   中英

click handler firing multiple times, unbind not working

I have a problem with my jQuery click handler. It seems to be firing more than once when I click it. I tried using the .unbind method, but that broke my other jQuery. Why does this happen? I am attempting to build a calculator app and I want the numbers when clicked to be pushed to an array. The function works, it just does it too many times. Here is my javascript. Each button is a div with it's resepctive class, ie the "7" button is .seven.

Here is the code

$(document).ready(function(){
$("#hidden > div").mouseover(function(){
    $(this).css('background-color','red');
$("#hidden > div").mouseleave(function(){
    $(this).css('background-color','black');
$("div.seven").click(function(){
    primary.push(7);
});
$("div.eight").click(function(){
    primary.push(8);
});
$("div.nine").click(function(){
    primary.push(9);
});
$("#.equals").click(function(){
alert(primary);
});
});
});
});
</script>

Because every time mouse enters to a div inside the #hidden element you are registering a click/mouseleave handler.

Under normal circumstances you should not register a event handler inside one.

Try

$(document).ready(function () {
    var primary = [];
    $("#hidden > div").mouseover(function () {
        $(this).css('background-color', 'red');
    });
    $("#hidden > div").mouseleave(function () {
        $(this).css('background-color', 'black');
    });
    $("div.seven").click(function () {
        primary.push(7);
    });
    $("div.eight").click(function () {
        primary.push(8);
    });
    $("div.nine").click(function () {
        primary.push(9);
    });
    $("#.equals").click(function () {
        alert(primary);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM