How to do “If Clicked Else ..”

后端 未结 8 1554
灰色年华
灰色年华 2021-01-31 05:48

I am trying to use jQuery to do something like

if(jQuery(\'#id\').click) {
    //do-some-stuff
} else {
    //run function2
}

But I\'m unsure h

相关标签:
8条回答
  • 2021-01-31 06:18

    if you press x, x amount of times you will get the division of the checkbox by y which results into a jquery boxcheck which would be an invalid way to do this kind of thing. I hope you will have a look at this before using the .on() functions

    0 讨论(0)
  • 2021-01-31 06:20

    A click is an event; you can't query an element and ask it whether it's being clicked on or not. How about this:

    jQuery('#id').click(function () {
       // do some stuff
    });
    

    Then if you really wanted to, you could just have a loop that executes every few seconds with your // run function..

    0 讨论(0)
  • 2021-01-31 06:23

    Maybe you're looking for something like this:

    $(document).click(function(e)
       {
           if($(e.srcElement).attr('id')=='id')
           {
               alert('click on #id');
           }
           else
           {
                alert('click on something else'); 
           }
       });
    

    jsfiddle

    You may retrieve a pointer to the clicked element using event.srcElement .

    So all you have to do is to check the id-attribute of the clicked element.

    0 讨论(0)
  • 2021-01-31 06:26
     var flag = 0;
    
     $('#target').click(function() {
        flag = 1;
     });
    
     if (flag == 1)
     {
      alert("Clicked");
     }
     else
     {
       alert("Not clicked");
     }
    
    0 讨论(0)
  • 2021-01-31 06:30

    You should avoid using global vars, and prefer using .data()

    So, you'd do:

    jQuery('#id').click(function(){
      $(this).data('clicked', true);
    });
    

    Then, to check if it was clicked and perform an action:

    if(jQuery('#id').data('clicked')) {
        //clicked element, do-some-stuff
    } else {
        //run function2
    }
    

    Hope this helps. Cheers

    0 讨论(0)
  • 2021-01-31 06:36

    The way to do it would be with a boolean at a higher scope:

    var hasBeenClicked = false;
    jQuery('#id').click(function () {
        hasBeenClicked = true;
    });
    
    if (hasBeenClicked) {
        // The link has been clicked.
    } else {
        // The link has not been clicked.
    }
    
    0 讨论(0)
提交回复
热议问题