2014-12-23 21 views
1

我有jQuery代碼像這樣它使用的類名作爲選擇已經存在的文件中:如何讓現有的jQuery選擇HTML插入DIV作爲字符串

jQuery(".rego-close").click(function(){ 
    //on-click events  
}); 

然後我有一個Ajax請求其生成HTML的一個大型複雜的字符串,並通過HTML()函數將它變成一個div:

jQuery.ajax({ 
     type: "POST", 
     url: "outputscript.php?event_id="+var1+"&course_id="+var2, 
     dataType: "html", 
     success: function(data, textStatus, jqXHR){ 
      jQuery("#data_target_div").html(data); 
      //outputs stuff like: "<div class='something' id='something1'><div><a href='#' data-customAttribute='monkey'>Complex html</a><i>stuff</i></div></div>" 
     } 
}); 

的HTML加載到DIV正確,但是我的jQuery選擇不會針對新生成的HTML裏面的內容。

在過去,我用事件代表團瞄準新的內容,如:

$('.container').on('click','.remove',function(){ 
    alert("remove"); 
}); 

但我有太多的代碼,回去重寫一切。

是否有一種簡單的方法將大型多嵌套HTML字符串添加到DOM中,以便現有的jQuery代碼能夠將其中的元素作爲目標?

感謝

+1

你就是不行。事件代表團只能這樣做。否則,在屬性中的onclick處理程序和單擊元素的對象一起寫入。 –

+0

...我很害怕有人會這樣說:( –

+0

在'data_target_div'上像'$('#data_target_div')那樣嘗試委託on('click','div',function(){...} );' – waki

回答

0

看,如果這個破解工作 -

jQuery.ajax({ 
     type: "POST", 
     url: "outputscript.php?event_id="+var1+"&course_id="+var2, 
     dataType: "html", 
     success: function(data, textStatus, jqXHR){ 

     var scr = '<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>'; //jQuery library 
     jQuery('body').prepend(scr); //recall library 

      jQuery("#data_target_div").html(data); 
      //outputs stuff like: "<div class='something' id='something1'><div><a href='#' data-customAttribute='monkey'>Complex html</a><i>stuff</i></div></div>" 
     } 
}); 
+1

很酷的想法,但我不能讓它工作不幸,另外我不想在ajax請求上重新加載jQuery庫,這會在我的腳本上留下一些嚴重的滯後時間。 –