开发者

Jquery function firing

A q开发者_如何学Pythonuick question really.. Could someone explain why the first example would work, yet the second does not.

   $(function()
   {  
      $("#select_one").change(function() 
      {
         alert('efjwelf');
      });
   });

### Example 2

  $("#select_one").change(function() 
  {
     alert('efjwelf');
  });

Thanks in advance


Because the #select_one object doesn't exist until the DOM is fully loaded. $function(){...}) is shorthand for $(document).ready(function() {...})


In the second example, the element you are binding (#select_one) to does not exist yet, so the event listener doesn't get binded to anything.

When you call bind (or change, or other shortcut methods), the event listener only gets attached to the elements that the selector matches at that time. Elements added in the future do not get attached. To get around this, these methods are used:

  • $(document).ready(function(){/*...*/}) or $(function(){/*...*/}) - This makes sure the document is ready before attaching events.
  • $("selector").live(function(){/*...*/}) - This attaches the listener to all elements that match the selector, now or in the future.
  • $("root").delegate("selector", "click", function(){/*...*/}) - This attaches the listener to all elements that match the selector with a root elements, now or in the future.


On the second one, element that you are trying to attach an event handler is not available yet.

Check this: http://api.jquery.com/ready/

All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)


It's a matter of when the DOM is ready/loaded.


if element with id='select_one' exists at the time of execution of both scripts - they will both work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜