Checkbox inside an anchor click behavior

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

Consider following snippet:



    
        

        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    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");
        }
    });
    

提交回复
热议问题