开发者

How to run code inside .live() on document ready?

开发者 https://www.devze.com 2023-01-08 06:01 出处:网络
$(\'#foo\').live(\'keyup\', function (e) { var input = $(this).val(); // code to process input }); This is used in a post form and I need to run the code inside the live()开发者_如何转开发 when the
$('#foo').live('keyup', function (e) {
  var input = $(this).val();
  // code to process input
});

This is used in a post form and I need to run the code inside the live()开发者_如何转开发 when the document is ready. Is there a way, other than to wait for a key press, to invoke it?


$(function() { 
   // add the event
  $('#foo').live('keyup', function (e) { 
  var input = $(this).val(); 
      // code to process input 
    }); 
  $('#foo').trigger('keyup');  //trigger the event
}); 


It sounds like you're saying that there's a part of the code that will run on keyup that you also want to run once when the page loads.

If that's the case, you can place that code inside another function, and call it both on page load and inside the .live() handler.

function someFunction() {
   // code to run
}

$('#foo').live('keyup', function (e) {
  var input = $(this).val();
    // run on keyup
  someFunction();
});

   // run on page load
someFunction();


If you're asking how to attach the keyup event after the document is ready, this is the sollution:

jQuery(document).ready(function($) {

    $('#foo').live('keyup', function (e) {
      var input = $(this).val();
      // code to process input
    });

});

However, this would have no function, because the whole idea of heaving jQuery.live is to automaticly bind to each selector, now and in the future.

Also, you're specifing an ID as the selector. The id must be unique to an element. Thus being able to bind it to multiple elements with the ID foo would be technically incorrect.

0

精彩评论

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