如何在动态创建的元素上调用Jquery Function

时间:2015-04-30 05:12:11

标签: jquery datepicker

这里我想在class =" datepickers"上调用datepicker()函数。这是动态创建的。

如果我试图调用jQuery的datepickers(),那么它就无法正常工作。

请任何人都可以。

  $("#add").click(add);
  $("#remove").click(remove);


         $(".datepickers").datepicker();


});

function remove(){

     // alert("hello");
     if(typeof remove.i=='undefined')
            remove.i=0;

     alert(remove.i);


    $("#from"+remove.i).remove();
    $("#to"+remove.i).remove();
    $("#timeLabel"+remove.i).remove();
     $("#tLabel"+remove.i).remove();
      $("#fLabel"+remove.i).remove();
      if(remove.i!=0)
            remove.i--;
  }
  function add(){

      if(typeof remove.i=='undefined')
          remove.i=0

    remove.i++;
      //alert(remove.i);
      var id1="'from"+remove.i+"'";
      alert(id1);
     var data= "<label id='timeLabel"+remove.i+"'>Offer Time ::: </label>"+
                "<label id='fLabel"+remove.i+"'>From &nbsp;&nbsp;&nbsp;  </label><input type='date'  class='datepickers' id='from"+remove.i+"' >"+
                "<label id='tLabel"+remove.i+"'>   To&nbsp;&nbsp;&nbsp;  </label><input type='date'  class='datepickers' id='to"+remove.i+"'>";
      alert(data)  ;


  $("#addDiv").append(data);

  }                          

1 个答案:

答案 0 :(得分:1)

对于动态添加的元素,您需要在创建这些元素后初始化插件,以便

function add() {

    if (typeof remove.i == 'undefined') remove.i = 0

    remove.i++;
    //alert(remove.i);
    var id1 = "'from" + remove.i + "'";
    alert(id1);
    var data = "<label id='timeLabel" + remove.i + "'>Offer Time ::: </label>" +
        "<label id='fLabel" + remove.i + "'>From &nbsp;&nbsp;&nbsp;  </label><input type='date'  class='datepickers' id='from" + remove.i + "' >" +
        "<label id='tLabel" + remove.i + "'>   To&nbsp;&nbsp;&nbsp;  </label><input type='date'  class='datepickers' id='to" + remove.i + "'>";
    alert(data);

    var $el = $(data).appendTo('#addDiv');
    //for newly created datepicker initialize the plugin
    $el.find(".datepickers").datepicker();

}