【问题标题】:forward parent event to child using query使用查询将父事件转发给子事件
【发布时间】:2016-01-20 01:03:51
【问题描述】:

我的父 div 包含一个隐藏的表单元素(输入):

$(document).ready(function () {

    $('.parent').on('click', function (event) {
        $(this).toggleClass('active');
		$(this).find('.child').trigger('click');
    });


    $('.child').on('click', function (event) {
      var theMsg = event.altKey ? 'true' : 'false';
       $('.parent span').html(theMsg);
    });

});
.parent {
    width:100px;
    height: 100px;
    background: #eee;
}
.child {
    display:none;
}
.active {
    background: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
    ALT: <span> </span>
    <input class='child'>
</div>

当我的父点击处理程序被调用时,我会注意是否按下了 ALT 键。我正在尝试为隐藏的输入元素触发('click'),并传递 altKey 状态。我没有尝试过让这种情况发生。我错过了什么?

【问题讨论】:

    标签: jquery events


    【解决方案1】:

    我不确定您使用的是哪个浏览器或操作系统平台。我的代码用 ubuntu chromium 测试过。

    在铬浏览器中用于选择菜单选项的 Alt 键。

    供您参考:

    event.altKey not working in chrome and IE

    所以,你可以使用 Clt 键或 Shift 键。

    你也可以看看

    jQuery: How to catch keydown + mouse click event?

        $(document).ready(function() {
    
      $(".parent").on('click', function(e) {
        console.log(e.altKey, e.ctrlKey, e.shiftKey);
        var theChild = $(this).find('.child');
        theChild.trigger('click');
      });
    
      $(".child").on('click', function(e) {
        e.stopPropagation();
        console.log('child');
      });
    
    });
    

    如果有任何问题,请告诉我。

    【讨论】:

    【解决方案2】:

    点击事件有语法错误。在click 之后,您有额外的)。应该是:

    $('.parent').on('click',function(event) {
     var theChild=$(this).find('.child');
     theChild.trigger('click');
    });
    

    【讨论】:

    • 是的,我复制代码时出现了转录错误。问题依然存在。
    • @user1307065:你能在小提琴中重现这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2020-01-15
    • 2013-05-13
    • 1970-01-01
    • 2021-11-07
    相关资源
    最近更新 更多