avatasia
V2EX  ›  jQuery

jQuery的事件执行顺序问题,求解

  •  
  •   avatasia · Jul 22, 2011 · 8493 views
    This topic created in 5412 days ago, the information mentioned may be changed or developed.
    伪代码如下:
    <input id="btn1" type="submit" value="提交" />

    $("btn1").click(function(){
    alert('a');
    });

    $("btn1").click(function(){
    alert('b');
    });

    上面两个事件都会响应,请问,怎么处理才能只触发其中一个事件,两个方法都要有。
    7 replies    2014-05-26 16:57:08 +08:00
    reus
        1
    reus  
       Jul 23, 2011
    “只触发其中一个事件,两个方法都要有”什么意思?
    如果想顺序可以用queue机制
    sparklo
        2
    sparklo  
       Jul 23, 2011
    click事件只有一个, 你不加条件判断怎么可能想让他区别两种回应呢?
    chone
        3
    chone  
       Jul 23, 2011
    在不需要的触发的时候删除掉handler

    var handlerA = function() {alert('a');};
    var handlerB = function() {alert('b');};
    var btn = $("btn1");

    // fire a
    btn.bind('click', handlerA);
    // fire b
    btn.unbind('click', handlerA);
    btn.bind('click', handlerB);

    或者加一个条件变量,当'click'事件被触发的时候再判断是否执行handler
    var fireA = true;
    var handlerA = function() {if (!fireA) return; alert('a');};
    var handlerB = function() {fi (fireA) return; alert('b');};
    // fire handler b
    fireA = false;
    avatasia
        4
    avatasia  
    OP
       Jul 23, 2011
    貌似思路都不错,
    在网上找到这篇文章

    http://shawphy.com/2009/04/how-to-use-queue-and-dequeue.html
    ashchan
        5
    ashchan  
       Jul 23, 2011
    如果你只是想让每次点击时,只响应两个回调中的一个(换句话说两个方法轮流执行),那么只要用toggle就行:

    $("#btn1").toggle(function(){ /*handler 1*/ }, function(){ /*handler 2*/ });
    yangg
        6
    yangg  
       Jul 23, 2011
    $("#btn1").click(function(e){
    alert('a');
    e.stopImmediatePropagation();
    });
    Honwhy
        7
    Honwhy  
       May 26, 2014
    @ashchan 我有一个场景,由于第三方元素的影响,toggle所要表现的顺序被打乱了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3044 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 09:40 · PVG 17:40 · LAX 02:40 · JFK 05:40
    ♥ Do have faith in what you're doing.