Friday, March 31, 2017

How to add an event handle to dynamic generated HTML content?

when we have a static web content, we can add an javascript function to the element on Doccument.ready Event.

<table><tr id="myRow"><td></td></tr><table>

in  $(document).ready(function () {
    $("myRow").onClick(function(event){
        var $this = $(this);
        var tbody= $(this).closest('tbody').next('tbody');
        if (tbody.hasClass("collapsed")) {
            var img=$this.find('.expandImg');
            $this.find('.expandImg').attr("src","/_layouts/images/minus.gif");
            tbody.removeClass("collapsed");
        } else {
            tbody.addClass("collapsed");
            $this.find('.expandImg').attr("src","/_layouts/images/plus.gif");
        }
}

However, if the html content is created in the fly. then click event no longer work,
we should use the .live() instead of onClick
$(".myRow").live('click', function(event){
        var $this = $(this);
        var tbody= $(this).closest('tbody').next('tbody');
        if (tbody.hasClass("collapsed")) {
            var img=$this.find('.expandImg');
            $this.find('.expandImg').attr("src","/_layouts/images/minus.gif");
            tbody.removeClass("collapsed");
        } else {
            tbody.addClass("collapsed");
            $this.find('.expandImg').attr("src","/_layouts/images/plus.gif");
        }

No comments:

Post a Comment