假设我有一个带有onclick事件的元素,里面还有另一个元素,如何禁用子元素的onclick事件?
示例:
谢谢。
示例:
text
当你选中复选框时,不应触发onclick事件。谢谢。
<h3 onclick="do something"><input type="checkbox" name="child" onclick="return false;" /> text</h3>
function onlick_handler(e)
{
e.stopPropagation(); //this event would propagate to parents of this object which are clicked as well
// the rest here
}
您的处理程序(即 h3 标签中的“do something
”部分)可以检查源元素的 tagName
:
var origin = event.srcElement || event.target;
if (origin.tagName && origin.tagName.match(/h3/i)){
// do things
} else {return true;}
现在对于复选框,点击处理程序已经被触发,但是不会发生任何事情。或者,您可以为h3标签提供唯一的id,并检查所点击元素的id。
我可以建议在类似问题中提供的这个答案吗?
上面是我复制的原始答案:
我有一个与你第一个问题非常相似的问题。但不是针对 <div> 和复选框,而是针对一个表格。看一下我的无法工作的代码:
<table>
<tr onClick="alert('I expect this alert when Cell_1 or Cell_2 are clicked but not Cell_3')">
<td>Cell_1</td>
<td>Cell_2</td>
<td onClick="alert('I expect this alert only when Cell_3 is clicked')">Cell_3</td>
</tr>
<table>
第一个警报是:
"我只期望在点击 Cell_3 时出现此警报"
第二个警报是:
我希望当 Cell_1 或 Cell_2 被点击时出现此警报,但不包括 Cell_3.
搜索如何解决这个问题,我发现了this briliant帖子在Quirksmode上。
简而言之,我可以通过以下方式解决这个难题:
<table>
<tr onClick="alert('I expect this alert when Cell_1 or Cell_2 are clicked but not Cell_3')">
<td>Cell_1</td>
<td>Cell_2</td>
<td onClick="Cell_3Alert(event)">Cell_3</td>
</tr>
<table>
并且JavaScript:
function Cell_3Alert(e) {
alert('I expect this alert only when Cell_3 is clicked');
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
我已经测试过,它可以在FireFox 3.6+、IE6+和Chrome上运行。
希望这有所帮助!
您可以为复选框设置一个 onClick 事件,如果该框被选中,则将 h3.onClick 属性设置为空白,否则将其设置为正确的函数引用。