jQuery - How do I bind events to hidden elements that will be shown later?

后端 未结 6 1149
花落未央
花落未央 2020-12-08 00:15

I am trying to attach \'click\' events to all elements of a particular class. The problem is some of the elements are on a tab that is hidden (display: none) at the time tha

相关标签:
6条回答
  • 2020-12-08 00:41

    Use delegate (note this is after you unhide them):

    $('body').delegate('.someClass', 'click', function (evt) {
        // do something here
    });
    
    0 讨论(0)
  • 2020-12-08 00:43

    As of jQuery 1.7, the .live() method is deprecated.

    You can now use the .on() method. By attaching a delegated event to an element that is viewable in the HTML when the jQuery is run.

    So if a.someClass is hidden when jQuery is run, you should attach a delegated event to the body, so it will run when there is a viewable a.someClass element in the future, for example:

    $('body').on('click','input.a.someClass',function(){
      alert("test");
    });
    
    0 讨论(0)
  • 2020-12-08 00:45

    Times have changed, it would now be done using ".on"

    .on('click',function(){/* code */});

    0 讨论(0)
  • 2020-12-08 00:52

    edit 2 years later: As some people pointed out, the Live function is now deprecated (as you can also see at the top of the linked docs page). The right event handler name for the current version would be On. See Maxim's answer for a good example.

    Original answer:
    Have you tried using Live()?

    .live('click',function(){/* code */});
    

    ?

    version note: live has been deprecated in jQuery 1.7 and it was removed in jQuery 1.9. This answer is only correct for jQuery versions older than jQuery 1.7

    0 讨论(0)
  • 2020-12-08 00:53

    According to the jquery documentation at http://api.jquery.com/live/

    Attach a handler to the event for all elements which match the current selector, now and in the future

    Here is an example of how to use it:

    <!DOCTYPE html> 
    <html> 
    <head> 
      <style> 
      p { background:yellow; font-weight:bold; cursor:pointer;  
              padding:5px; } 
      p.over { background: #ccc; } 
      span { color:red; } 
      </style> 
      <script src="http://code.jquery.com/jquery-1.5.js"></script> 
    </head> 
    <body> 
      <p>Click me!</p> 
    
      <span></span> 
    <script> 
        $("p").live("click", function(){ 
          $(this).after("<p>Another paragraph!</p>"); 
        }); 
    </script> 
    
    </body> 
    </html>
    
    0 讨论(0)
  • 2020-12-08 00:54

    Use

    $('parentelement').on('click','taget element',function(){
    
    })
    

    parentelement should be visible at page load

    0 讨论(0)
提交回复
热议问题