2014-08-28 42 views
-1

當條件返回true時,我有許多按鈕必須自行阻止。像打擊沒有工作。如何做到優雅?條件許多處理程序

$('#button1,#button2,#button3').click(function(event){ 
    if(maintence_mode){ 
     event.preventDefault(); // alerts can't be shown 
    } 
}); 

$('#button1').click(function(){ 
    alert('1'); 
}); 

$('#button2').click(function(){ 
    alert('2'); 
}); 

$('#button3').click(function(){ 
    alert('3'); 
}); 

jsfiddle

更新: 我有完全類似下面現在不event.stopImmediatePropagation()工作。我認爲,請求/isservicemode需要一些時間......

var checkServiceMode = function(callback) { 
    $.get('/isservicemode', function(data){ 
     callback(data.mode); 
    }); 
} 

$('#button1,#button2,#button3').click(function(event){ 
    checkServiceMode(function(modeon){ 
     if(modeon) { 
      event.preventDefault(); 
      event.stopImmediatePropagation(); 
      return false; 
     } 
    }); 
}); 
+1

怎麼樣一個簡單的返回FALSE; ?條件滿足時。 – SSA 2014-08-28 11:49:03

回答

0
var maintence_mode = true; 

$('#button1,#button2,#button3').click(function(event){ 
     if(maintence_mode){ 
      event.preventDefault(); // alerts can't be shown 
     } 
     else{ 
      alert($(this).text().split("")[1]) 
     } 
}); 

DEMO

+0

'警報'只是簡化示例的填充程序 – marioosh 2014-08-28 11:53:42

0

你應該在別的街區管理代碼:

var maintence_mode = true; 
$('#button1,#button2,#button3').click(function(event){ 
     if(maintence_mode){ 
      event.preventDefault(); // alerts can't be shown 
     } else{ 
      $('#button1').click(function(){ 
     alert('1'); 
    }); 

    $('#button2').click(function(){ 
     alert('2'); 
    }); 

    $('#button3').click(function(){ 
     alert('3'); 
    }); 
     } 
    }); 
1

你可以stopImmediatePropagation。 Demo

爲了演示目的,我在5秒後將mainence_mode重置爲false,以便再次點擊。

var maintence_mode = true; 


$('#button1,#button2,#button3').click(function(event){ 
     if(maintence_mode){ 
      event.preventDefault(); // alerts can't be shown 
      event.stopImmediatePropagation(); 
      return false; 
     } 
    }); 
    $('#button1').click(function(){ 
     alert('1'); 
    }); 

    $('#button2').click(function(){ 
     alert('2'); 
    }); 

    $('#button3').click(function(){ 
     alert('3'); 
    }); 

setTimeout(function(){ 
maintence_mode = false; 
},5000); 
+0

http://api.jquery.com/event.stopimmediatepropagation/ – Satpal 2014-08-28 11:55:13

0

使用事件停止傳播功能。

演示:http://jsfiddle.net/e5mkvrjq/

var maintence_mode = true; 
$('#button1,#button2,#button3').click(function(event){ 
    if(maintence_mode){ 
     event.stopPropogation(); // alerts can't be shown 
    } 
}); 

$('#button1').click(function(){ 
    alert('1'); 
}); 

$('#button2').click(function(){ 
    alert('2'); 
}); 

$('#button3').click(function(){ 
    alert('3'); 
}); 
+0

儘管此鏈接可能回答此問題,但最好在此處包含答案的基本部分,並提供鏈接供參考。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – Syon 2014-08-28 12:17:33

+0

@Syon Answere更新。 – Shail 2014-08-28 12:25:00