Pregunta

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');
¿Fue útil?

Solución

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..

Otros consejos

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

$(document).ready(function(){
    $('#hdimage').on("click", function(){
        alert("dostuff")
    });
    $('#hdimage').triggerHandler('click');
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top