I am adding a click event to a checkbox which will show/hide additional fields depending on its checked status. I want the handler to fire on load to set up the initial page structure. For some reason triggerHandler is not working on the field. If I change it to 'trigger' the handler will fire, but the checkbox status will also change. Can you see what i've done wrong/why triggerHandler won't work?

$('body').on("click", "#hdimage", function(){
    console.log('hd');
    if(!$('#hdimage').is(':checked')){
        $('.sd-dim').hide();
    } else {
        $('.sd-dim').show();
    }
});
$('#hdimage').triggerHandler('click');
有帮助吗?

解决方案

That happens (as described in the docs) because

Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

and since you use the delegated syntax of the .on() method which lets body handle the click event that occurs on the #hdimage element, that event never reaches the body..

其他提示

Your Event is not bound to "#hdimage" its bound to 'body'

$(document).ready(function(){
    $('#hdimage').on("click", function(){
        alert("dostuff")
    });
    $('#hdimage').triggerHandler('click');
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top