Inner div受外部div的onclick影响 [英] Inner div affected by outer div's onclick
问题描述
问题: 我试过了: HTML: JS: 注意:我使用toggle() show()是因为我在初始显示原始网页中按钮的表单时使用了相同的功能。
单击内部div会触发外部div的onClick事件。在这种情况下,它会切换外部< div>
,inner < div>
和< p>
元素。
在内部div上设置高于外部div的 z-index 。
$ b
< div id ='messageForm'onClick = toggleMessageForm()>
< div class =innerBox>
< p>嗨!< / p>
< / div>
< / div>
function toggleMessageForm(){
$('#messageForm')。toggle();
}
完全删除 onClick
属性,然后用jQuery连接处理程序:
< ();
toggleMessageForm();
}); code $
将它放在脚本中
在HTML中比 div
(或者将其包装在 ready
处理程序中)。
evt.stopPropagation
取消点击事件的冒泡(停止传播),所以它不会到达父div。
如果你确实想要保留 onClick
属性,您可以这样做:
< div id ='messageForm'onClick =toggleMessageForm(event);>
...然后在 toggleMessageForm
中:
函数toggleMessageForm(evt){
if(evt.stopPropagation){
evt.stopPropagation() ;
}
else {
evt.cancelBubble = true;
}
$('#messageForm')。toggle();
}
...但是,如果您已经在使用jQuery,那将是不寻常的。
Problem:
Clicking of the inner div triggers the onClick-event of the outer div. In this case it toggles the visibility of the outer <div>
, inner <div>
and the <p>
element.
What I've tried:
Setting the z-index higher on the inner div than the outer div. No effect.
HTML:
<div id='messageForm' onClick=toggleMessageForm() >
<div class="innerBox">
<p>Hi!</p>
</div>
</div>
JS:
function toggleMessageForm(){
$('#messageForm').toggle();
}
Note: The reason I'm using toggle() instead of show() is because I am using the same function when initially showing the form from a button in the original webpage.
Remove the onClick
attribute entirely, and instead hook up the handler with jQuery:
$("#messageForm").click(function(evt) {
evt.stopPropagation();
toggleMessageForm();
});
Put that in a script
element lower down in the HTML than the div
(or wrap it in a ready
handler).
evt.stopPropagation
cancels the bubbling (stops the propagation) of the click event, so it doesn't reach the parent div.
If you really, really want to keep the onClick
attribute, you can do this instead:
<div id='messageForm' onClick="toggleMessageForm(event);">
...and then in toggleMessageForm
:
function toggleMessageForm(evt){
if (evt.stopPropagation) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
$('#messageForm').toggle();
}
...but as you're already using jQuery, that would be unusual.
这篇关于Inner div受外部div的onclick影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!