简体   繁体   中英

JQuery Event binding of Ajax Loaded content

I am trying to get JQuery to work on dynamically loaded content through ajax with event binding, similar to this: Event binding on dynamically created elements?

However, I am not that good with java/Jquery and I cant seem to get jquery to work on the ajax content. I started with this code:

(function($){
function floatLabel(inputType){
        $(inputType).each(function(){
            var $this = $(this);
            var text_value = $(this).val();

            // on focus add class "active" to label
            $this.focus(function(){
                $this.next().addClass("active");
            });

            // on blur check field and remove class if needed
            $this.blur(function(){
                if($this.val() === '' || $this.val() === 'blank'){
                    $this.next().removeClass();
                    }
            });

            // Check input values on postback and add class "active" if value exists
            if(text_value!==''){
                $this.next().addClass("active");
                }
            });
    // Automatically remove floatLabel class from select input on load
    //$( "select" ).next().removeClass();
}
// Add a class of "floatLabel" to the input field
floatLabel(".floatLabel");
});

And I tried to bind the events like this:

(function($){
    var $this = $('.floatLabel');
    var text_value = $('.floatLabel').val();
$('.container').on('focus', '.floatLabel', function floatLabel(inputType){
    $(inputType).each(function(){
        $this.next().addClass('active');
        if(text_value!==''){
            $this.next().addClass('active');
        }
    });
});
$('.container').on('blur', '.floatLabel', function floatLabel(inputType){
        $(inputType).each(function(){
            if($this.val() === '' || $this.val() === 'blank'){
                $this.next().removeClass();
        }
        });
    });
})(jQuery);

And this is the main html page:

<div class="container">
   <div id="ha">
     <script type="text/javascript">
      $( document ).ready(function() {
      $('#ha').load('example.com/createform');
});
     </script>
   </div>
</div>

Content loaded:

<div >
 <input class="floatLabel" name="example">
 <label for="example">example</label>
</div>

这似乎可以通过$(document).ajaxComplete (function (){来解决,只需复制原始代码即可。感谢大家的帮助!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM