5

当我单击 mainDiv 时,将调用该函数,当我单击 subDiv 时,mainDiv()将调用两个函数。mainDiv()subDiv()

subDiv()当我单击 subDiv 时,我只想调用该函数。我怎样才能做到这一点?

代码:

<div onclick="mainDiv()">
  show main div
  <div onclick="subDiv()">
    show sub div
  </div>
</div>
<script type="text/javascript">
  function  mainDiv(){
    alert("main div is clicked");
  }
  function  subDiv(){
    alert("sub div is clicked");
  }
</script>
4

4 回答 4

3

您可以在除 IE8 之外的所有浏览器中使用stopPropagation(以及来自同一公司的旧浏览器)。但是如果你想兼容,你应该使用quirksmode 中描述的解决方案:

   <div onclick="subDiv(event)">

   function  subDiv(e){
     e.cancelBubble = true;
     if (e.stopPropagation) e.stopPropagation();
     alert("sub div is clicked");
   }

示范

于 2013-03-07T12:16:52.547 回答
3

采用e.stopPropogation()

HTML

<div onclick="subDiv(event)">  //<--- pass event parameter

脚本

function  subDiv(e){    

   if(e.stopPropagation){  // check stoppropogation is avilable
      e.stopPropagation();  //use stopPropogation
   }else{
      e.cancelBubble = true;  // for ie8 and below
   }
   alert("sub div is clicked");
}
于 2013-03-07T12:18:24.137 回答
1
<script type="text/javascript">
function mainDiv() {
    alert("main div is clicked");
}
function subDiv(e) {
    if (!e)
        e = window.event;

    //IE9 & Other Browsers
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    //IE8 and Lower
    else {
        e.cancelBubble = true;
    }
    alert("sub div is clicked");

}

于 2013-03-07T12:23:00.753 回答
0

试试这个

    <div onclick="mainDiv()">
      show main div
      <div onclick="subDiv(event);">
        show sub div
      </div>
    </div>
    <script type="text/javascript">
      function  mainDiv(){
        alert("main div is clicked");
      }
      function  subDiv(arg){
        arg.stopPropagation();
        alert("sub div is clicked" + arg);

      }
</script>

要支持 IE 8 及更低版本,请使用 arg.cancelBubble

于 2013-03-07T12:20:27.830 回答