【问题标题】:calling different functions from different divs从不同的div调用不同的函数
【发布时间】:2018-06-01 10:43:16
【问题描述】:

我有这样的结构

<div onclick="first()">
//first div
<div onclick="second()">
//second div
<div onclick="third()">
//my content here inner div
</div>
</div>
</div>

当我点击任何 div 时,它会调用第一个函数。如何实现只有我点击的div然后调用对应函数的情况。我是 javascript 新手。

【问题讨论】:

标签: javascript


【解决方案1】:

由于您的 DIV 相互嵌套,因此单击事件将冒泡到每个元素。如果您只希望它位于您单击的内部 DIV 上,则需要调用 event.stopPropagation() 以停止冒泡。这意味着您必须将 event 对象传递给函数。

<div onclick="first(event)">
//first div
<div onclick="second(event)">
//second div
<div onclick="third(event)">
//my content here inner div
</div>
</div>
</div>

那么函数必须是这样的:

function first(e) {
    e.stopPropagation();
    // rest of code here
}

【讨论】:

    【解决方案2】:

    您可以使用event.stopPropagation() 阻止click 事件冒泡。

    function first(){
      this.event.stopPropagation();
      alert( 'first div' );
    }
    
    function second(){
      this.event.stopPropagation();
      alert( 'second div' );
    }
    
    function third(){
      this.event.stopPropagation();
      alert( 'third div' );
    }
    <div onclick="first()">
    //first div
      <div onclick="second()">
      //second div
        <div onclick="third()">
          //my content here inner div
        </div>
      </div>
    </div>

    【讨论】:

      【解决方案3】:

      试试Event.stopPropagation(),它可以防止当前事件在捕获和冒泡阶段进一步传播。

      function first(e){
        e.stopPropagation();
        alert('first function')
      }
      function second(e){
        e.stopPropagation();
        alert('second function')
      }
      function third(e){
        e.stopPropagation();
        alert('third function')
      }
      <div onclick="first(event)">
        first div
        <div onclick="second(event)">
          second div
          <div onclick="third(event)">
            my content here inner div
          </div>
        </div>
      </div>

      【讨论】:

        【解决方案4】:

        问题是单击子 div 会触发该 div 的每个父级(单击第三个将触发第二个将首先触发)。为防止传播,您需要像这样stopPropagation See onclick documentation

        function first(e){
          e.stopPropagation();
          console.log('you are in first')
        }
        
        function second(e){
          e.stopPropagation();
          console.log('you are in second')
        }
        
        function third(e){
          e.stopPropagation();
          console.log('you are in third')
        }
        <div onclick="first(event)">
          //first div
          <div onclick="second(event)">
            //second div
            <div onclick="third(event)">
             //my content here inner div
            </div>
          </div>
        </div>

        【讨论】:

          猜你喜欢
          • 2021-01-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-04
          • 2021-06-04
          • 2014-09-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多