开发者

jquery .load not applying ready function

On document ready I run this code:

 jQuery(document).ready(function(){  
        jQuery('#button').click(function() {
            jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt");
            return false;
        });
    });

Then if I create a form like

<div id="contact_form">
  <form name="contact" method="post" action="">
    <fieldset>
      <label for="name" id="name_label">Name</label>
      <input type="text" name="name" id="name" size="30" value="" class="text-input" />

      <label for="email" id="email_label">Return Email</label>
      <input type="text" name="email" id="email" size="30" value="" class="text-input" />

      <label for="ph开发者_开发百科one" id="phone_label">Return Phone</label>
      <input type="text" name="phone" id="phone" size="30" value="" class="text-input" />

        <br />
      <input type="submit" name="submit" class="button" id="button" value="Send" />
    </fieldset>
  </form>
</div>

Everything works fine. However, if I mimic the behavior I want in the actual app (the form is loaded dynamically after document.ready has already been executed. The jquery #button action does not get called and the form acts as if there is no javascript and just runs a post.

jQuery('#contact_form').load("/dynamicform.php");

Is there something that has to be done to .load() in order for the ready function to be applied to it?


Use .live() like this:

 jQuery(document).ready(function(){  
    jQuery('#button').live('click', function() {
        jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt");
        return false;
    });
});

Your element isn't there when you're adding the handler. You need to listen for the click in all cases...this is what .live() is for, is listens up at the DOM root for the click, whereas .click() isn't getting attached to anything because there are no elements that match the selector when you're calling it. live() listens for clicks on matching elements later.


The .ready event is called when the DOM is ready to be used, and therefore it won't be called when you dynamically load and insert something into an already existing DOM.

Also I believe that it is common practice to have a custom form submit work by attaching an event handler to the form, not the submit button. As it will also handle cases where the user submits the form in another way than clicking on the submit button. Example:

jQuery("#contact_form form").submit(function (event) {
    event.preventDefault();
    // Do your stuff...
})

(event.preventDefault(): http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29)


ready() is not applied after load(). Look in the doc for load(), you can probably specify a callback to be executed when the loading is done, in which you'll be able to reassign the click handler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜