js 标题不知怎么描述

怎么样才能点击h1标签的123456 不弹出"div"

<div style="border:1px solid red;width:100px;height:100px;" onclick="alert('div')">
    <h1 onclick="alert(123456)">
        123456
    <h1>
</div>
阅读 3k
3 个回答
         <div id="outer" style="border:1px solid red;width:100px;height:100px;">
            <h1 id="inner">123456<h1>
         </div>
        
        document.getElementById('outer').addEventListener('click',function(){
          alert('div');
        })
        document.getElementById('inner').addEventListener('click',function(e){
          //阻止冒泡
          e.stopPropagation();
          alert(123456);
        })
      stopPropagation()方法 http://www.w3school.com.cn/jsref/event_stoppropagation.asp

这其实是个js冒泡。现在你要做的是阻止冒泡事件。

<div class="parent">
    <h1 class="child">孩子</h1>
</div>

$('parent').click(function(){
  alert(1);
})
 $('.parent .child').click(function(event){
  event.stopPropagation();//阻止冒泡事件
  alert(2);
})

这没办法吧,你把函数写在html里面了,你要是写在 script 里面的话,可以在 h1 绑定的那个函数里面最后加 e.preventDefault(), (e是传入函数的一个事件对象),或者 加 return false。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题