受外部 div's onclick 影响的内部 div [英] Inner div affected by outer div's onclick

查看:27
本文介绍了受外部 div's onclick 影响的内部 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:
单击内部 div 会触发外部 div 的 onClick 事件.在这种情况下,它会切换外部

、内部

元素的可见性.

我尝试过的:
将内部 div 上的 z-index 设置为高于外部 div.没有效果.

HTML:

JS:

function toggleMessageForm(){$('#messageForm').toggle();}

注意:我使用toggle() 而不是show() 的原因是因为我在最初通过原始网页中的按钮显示表单时使用了相同的函数.

解决方案

完全移除 onClick 属性,而是使用 jQuery 连接处理程序:

$("#messageForm").click(function(evt) {evt.stopPropagation();切换消息表单();});

将其放在 HTML 中低于 divscript 元素中(或将其包装在 ready 处理程序中).

evt.stopPropagation 取消冒泡(停止传播) 的点击事件,因此它不会到达父 div.

如果你真的、真的想保留 onClick 属性,你可以这样做:

...然后在 toggleMessageForm 中:

function toggleMessageForm(evt){如果(evt.stopPropagation){evt.stopPropagation();}别的 {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.

这篇关于受外部 div&amp;#39;s onclick 影响的内部 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆