代码之家  ›  专栏  ›  技术社区  ›  axel

我可以在jQuery中使用点击功能吗?

  •  1
  • axel  · 技术社区  · 10 年前

    我有这个问题

    事实上,我有一些元素 <li> 元素,在这些元素上,我对它们应用了一个操作,很容易这样做:

    $('.panelTabs li').on('click', function () {
      // ..some operation that change some tab associated to the list
    });
    

    然后在我的代码中,我需要应用另一个单击操作,该操作必须检查我是否可以执行前一个操作。

    $('.panelTabs li').on('click', function (ev) {
      // ..some operation that makes some check
      if(bActiveRequests === 0){
        ev.stopPropagation();
      }
    });
    

    但是第一个函数在包含检查的第二个函数之前应用,所以当然我的 停止传播() 无法工作,因为它在之后执行。

    所以我想问,是否有一种方法可以在一个已经应用于同一元素的函数之前添加expect一个click函数。

    • 我考虑将该函数保存在变量中,然后从 ,然后添加我的函数,然后添加上一个函数。。。但这有点棘手,一点也不好。

    • 我可以在第一个JavaScript文件之前包含第二个JavaScript文件。但由于代码的原因,这也有点棘手。

    有什么想法吗?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Community CDub    7 年前

    至少有两种方法可以用来实现这一点(我相信其他人可能会想出更多的方法)。

    首先,您可以使用 setTimeout 延迟第二次单击并执行验证 先前的 第一次点击发生。

    下面是一个示例:

    var shouldCancel = false;
    //First event
    //Without the setTimeout, this event would be triggered first.
    $("#button1").click(function (e) {
        setTimeout(function () {
            if (!shouldCancel) {
                alert("test2");
            } // end if
        }, 500);
    });
    //Second event
    $("#button1").click(function (e) {
        //Perform validation checks here...
        alert("test1");
        shouldCancel = true;
        e.stopPropagation();
        e.preventDefault();
    });
    

    另一种选择(我更喜欢,也不那么麻烦)是使用“验证”方法,在单击时执行检查。

    $("#button2").click(function (e) {
        // ..some operation that makes some check and assigns a value to the "shouldCancel" property below
        $(document).trigger("should-continue", {
            shouldBeCanceled: shouldCancel,
            callback: function () {
                alert("test2");
            }
        });
    
    });
    
    $(document).bind("should-continue", function (e, data) {
        if (data.shouldBeCanceled) {
            e.stopPropagation();
            e.preventDefault();
            return;
        } else {
            alert("test1");
            data.callback(); // Call the method specified by the caller
        } // end if/else
    });
    

    这里有一个JSFiddle演示了这两种方法: http://jsfiddle.net/xDaevax/3ucby35x/

    下面是一些在JS中处理事件的有用链接:

        2
  •  0
  •   vis    10 年前

    只需将选择语句放在原始的单击处理程序中:

    $('.panelTabs li').on('click', function () {
        // ..some operation that makes some check
        if(bActiveRequests === 0){
            // ..some operation that change some tab associated to the list
        }
    });
    
        3
  •  0
  •   axel    10 年前

    我想到的另一个解决方案是添加一个类 残废 <li> 元素。一旦需要重新激活它,我将从 <li> .

    在常规设置中,我可以检查该类,如果它存在,那么将停止操作。

    $('.panelTabs li').on('click', function () {
      if($(this).hasClass('disabled')){
        ev.stopPropagation();
      }
    });