简体   繁体   English

触发器时,jquery triggerHandler不起作用

[英]jquery triggerHandler doesn't work while trigger does

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. 由于某种原因,triggerHandler不在该领域工作。 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? 你能看出我做错了什么/为什么triggerHandler不起作用?

$('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 ; 使用.triggerHandler()创建的事件不会冒泡DOM层次结构 ; 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 .. 并且由于您使用.on()方法的委托语法,该方法允许body处理#hdimage元素上发生的click事件,该事件永远不会到达body

Your Event is not bound to "#hdimage" its bound to 'body' 你的事件没有绑定到“#hdimage”它绑定到'body'

$(document).ready(function(){
    $('#hdimage').on("click", function(){
        alert("dostuff")
    });
    $('#hdimage').triggerHandler('click');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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