Monday, July 20, 2015

How to create a function in Jquery and added into an element? (jquery delegation)

I have a json data, and want to process it in Javascript and meanwhile generate a grid to append in  <form id="supplierFilter">.

The code is as following.

Javascript code:

 $(document).ready(function() {  
      var DTclass = ${class};  
      $.fn.classfunction = function() {  
            console.log("classes json:"+DTclass);  
          var columndiv;  
          var classes;  
          for (var i = 0; i < DTclass.length; i++) {  
               columndiv = $("<div class='col-sm-3'>");  
               classes = $("<div class='checkbox'>");  
               classes.append("<label> <input name='filter' value='"+DTclass[i].IMG_FILE_ID+"' type='checkbox'/>     <img src='${pageContext.request.contextPath}/download/"+DTclass[i].IMG_FILE_ID+"' alt='"+DTclass[i].DISPLAY_NAME+"' title='"+DTclass[i].DISPLAY_NAME+"'' /> "+DTclass[i].DISPLAY_NAME);  
               columndiv.append(classes);  
            $('#supplierFilter').append(columndiv);   
          }  
        };   
             $('#supplierFilter').classfunction();            
      )}    


HTML code:

 <form id="supplierFilter"></form>  


At beginning, I just use a regular javascript function, it did generate the html code, but when I clicked on the checkbox function, the function won't be triggered. This is caused by jquery delegation. There are more detail information from :
http://learn.jquery.com/events/event-delegation/

No comments:

Post a Comment