jQuery点击事件/事件冒泡问题,当尝试突出显示一个元素并同时选中一个复选框

jQuery click event / event bubbling issues when trying to highlight an element & check a checkbox at the same time

本文关键字:一个 事件 元素 复选框 显示 问题 jQuery      更新时间:2023-09-26

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

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

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

选项 2:对于这个,我尝试了另一种解决方案(删除了 .toggle() 方法)并试图找出实际单击的元素(console.log(e.target.nodeName);),现在我可以单击复选框但不能单击标签,而是标签不会使事件工作。

你能不能看看我的代码,看看我哪里出了问题,因为我相信它不会这么难......

干杯

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

$('.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();                
});

演示。