最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add click event and if condition together? - Stack Overflow

programmeradmin1浏览0评论

I need to perform some task based on 2 conditions on page load. 1) If a button is clicked or 2) If condition bees true

so can I bine this two events into one?

  if(x== true) || button.click(function(e){
..  
  perform task...       
}

I need to perform some task based on 2 conditions on page load. 1) If a button is clicked or 2) If condition bees true

so can I bine this two events into one?

  if(x== true) || button.click(function(e){
..  
  perform task...       
}
Share Improve this question asked Apr 8, 2014 at 14:55 user1298426user1298426 3,71715 gold badges62 silver badges116 bronze badges 3
  • I assume you mean if the condition bees true after the initialisation code for the page has finished executing? How does the condition bee true? As a result of code you're calling? – Anthony Grist Commented Apr 8, 2014 at 14:56
  • I am passing some variable from controller. If that is true or if button is clicked then perform some operation. – user1298426 Commented Apr 8, 2014 at 14:59
  • This is not how you're supposed to handle events... You should have 1 handler for click, calling a method, and then you're free to call the same method on any consition you need, whenever you need it... – Laurent S. Commented Apr 8, 2014 at 14:59
Add a ment  | 

3 Answers 3

Reset to default 3
var perform_task = function() {
    ....
}

if(x == true) perform_task();

button.click(function(er) { perform_task(); }

try this?

button.click(function(){
   if(x == true){
       /* do something */
   }
});
var flag = false;

$("button").click(function() { 

       flag = true;
});

 if((x== true) || flag ){

     // do here
}
发布评论

评论列表(0)

  1. 暂无评论