【问题标题】:Capturing an event with jquery使用 jquery 捕获事件
【发布时间】:2013-12-20 14:48:24
【问题描述】:

我有一个双重事件要处理。这两个事件都是“点击”,它们是用 jquery 处理的。 html如下:

 <div class="siteMap"  style="width:23%;">
            <h5>Divisione Anticontraffazione</h5>
            <span class="menufooter">
            <span class="link1"><a href="#scheda1">Introduzione</a></span><br>
            <span class="link2"><a href="#scheda2">Filosofia</a></span><br>
            <span class="link3"><a href="#scheda3">Negozio online</a></span></span><br>
        </div>

然后我的点击事件会在 menufooter 范围内和每个链接范围内触发。代码是这样的:

$(document).ready(function() {
    $('span.menufooter').click(function() { 
        //my code here
    });
    $("span.link1").click(function() {
       //my code here
    });
});

我需要一个事件捕获动作,点击 span menufooter 必须在点击 span link1 触发之前触发该事件。此时,这两个事件都没有触发。有什么提示吗?

【问题讨论】:

  • 为什么需要一个事件处理程序在另一个之前执行,顺序错误?
  • 我的回答让我有些沉闷,重新思考。谢谢@Barmar。
  • 也许可以更好地解释您的意图,以获得有关如何改进您的应用的一些建议。
  • 也许可以重新命名这个问题以更具体地说明您的问题。

标签: javascript jquery events event-capturing


【解决方案1】:

.menufooter 上的唯一火灾事件怎么样

$(document).ready(function() {
    $('span.menufooter').click(function(e) { 
        //my code here 1

        // Capture Event Propagation
        if ( $("span .link1").find(e.target).length>0 ){
           //my code here 2
        };
    });
});

http://jsfiddle.net/9QLtG/

【讨论】:

    【解决方案2】:

    您可以防止点击冒泡,然后触发对父元素的点击,因此该处理程序中的任何内容都会首先执行(除非它是异步的)

    $(document).ready(function () {
        $('.menufooter').click(function () {
            // fires before ....
        });
    
        $("span.link1").click(function (e) {
            e.stopPropagation();
            $('.menufooter').trigger('click');
            // .... this fires, as it's triggered above
        });
    });
    

    FIDDLE

    【讨论】:

      【解决方案3】:

      我会有 1 个点击监听器来监听包装器。您可以检查事件的目标,看看他们是否真的点击了链接并相应地运行代码。

      例如:

      $(document).ready(function() {
      
          $('.container').click(function(e) {
      
              // Perform action when they clicked in the main wrapper,
              // regardless of whether or not it was a link.
              console.log("I clicked in the wrapper...");
      
              if ($(e.target).hasClass('link')) {
                 // Perform action if they clicked on a link.   
                 console.log("...but more specifically, on a link.");
              }
          });
      
      });
      

      这是一个演示这个的小提琴:http://jsfiddle.net/WaYFr/

      【讨论】:

        【解决方案4】:

        试试这个event.stopPropagation();

         $("span.link1").click(function(event) {
             event.stopPropagation();
               ...
         });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-04-02
          • 1970-01-01
          • 1970-01-01
          • 2019-01-09
          • 1970-01-01
          • 1970-01-01
          • 2018-02-20
          • 2011-06-17
          相关资源
          最近更新 更多