Checkbox inside an anchor click behavior

前端 未结 4 750
逝去的感伤
逝去的感伤 2021-01-12 14:55

Consider following snippet:



    
        

        
相关标签:
4条回答
  • 2021-01-12 15:31

    here's a modified script

    var checkbox = $('<input type="checkbox"></input>');
    var a = $('#a');
    a.unbind("click").click(function(e) {
        e.preventDefault();
        checkbox.attr('checked', !checkbox.attr('checked'));
    });
    checkbox.prependTo(a);
    checkbox.click(function(e) {
        e.stopPropagation();
        // do something useful 
    });
    

    i unbind the click event on the <a> and rebind it with a event to check/uncheck the checkbox and also prevent the default.

    0 讨论(0)
  • 2021-01-12 15:46

    I know this is an old question but some may still be curious since it was never really fully answered without a messy hack or workaround. All you have to do is simply check where the event's target originated.

    So using your example (jsfiddle):

    // Don't change pages if the user is just changing the checkbox
    $("#a").click(function(e) {
        //e.preventDefault(); // Optional if you want to to keep the link from working normally
    
        alert("Click came from: " + e.target.tagName);
        if (e.target.tagName != "INPUT") {
            // do link
            alert("Doing link functionality");
        } else {
            // do something useful
            alert("Doing checkbox functionality");
        }
    });
    
    0 讨论(0)
  • 2021-01-12 15:47

    I Know this question is over 5 years old, but I had the same issue recently and the work-around I found was to add an onclick function to the checkbox and in that function call event.stopImmediatePropagation().

    from w3schools: "The stopImmediatePropagation() method prevents other listeners of the same event from being called"

    ie...the anchor.

    function checkbox_onclick(event){
    event.stopImmediatePropagation(); 
    }
    
    0 讨论(0)
  • 2021-01-12 15:48

    Well, it looks like a known Firefox bug, which leads to following link on checkbox click regardless of handlers' code. As a bit dirty workaround one can use:

    var checkbox = $('<input type="checkbox"></input>');
    checkbox.prependTo($('#a'));
    checkbox.click(function(e) {
        setTimeout(function() { checkbox.prop('checked', !checkbox.prop('checked')); }, 10);       
        // do something useful on clicking checkbox and but not surrounding link
        return false;
    });
    
    0 讨论(0)
提交回复
热议问题