【问题标题】:jQuery click event / event bubbling issues when trying to highlight an element & check a checkbox at the same time尝试突出显示元素并同时选中复选框时出现jQuery单击事件/事件冒泡问题
【发布时间】:2012-04-25 22:33:48
【问题描述】:

请看一下这个小提琴:http://jsfiddle.net/mrmartineau/53fkV/embedded/result/

预期结果是,当单击.poll_option td 时,背景颜色变为粉红色并选中复选框。每个选项都有不同的错误,它们是:

选项 1: 我遇到的问题是,在选项 1 上,当我单击复选框本身时,它不会检查,但其他一切正常。我的意思是当我点击标签和<td> 时,结果是正确的。看来事件没有正确冒泡..

选项 2: 对于这个,我尝试了另一种解决方案(删除了 .toggle() 方法)并试图找出实际点击的是什么元素(console.log(e.target.nodeName);),现在我可以点击复选框但不能点击标签,而不是标签让活动顺利进行。

请你看看我的代码,看看我哪里出错了,因为我确信它不会这么难......

干杯

【问题讨论】:

    标签: javascript checkbox click jquery


    【解决方案1】:

    提出的更简单的解决方案:

    $('.poll_option.one td').click(function (e) {
        $(this).toggleClass('highlight');
        $(this).find('input').prop("checked", $(this).hasClass("highlight"));
        console.log(e.target.nodeName);
    
    // weird that clicking the label does not naturally propagate
    // the click event to the parent
    }).find("label").click(function () {
        $(this).closest("td").click();                
    });
    

    Demo.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多