JQuery没有在Ajax加载页面中工作

我尝试以下,php文件,

//-----------------------------------------------------------------------------getData.php----------------------------------------------------------- <?php echo '   $(window.document).ready(function(){ $("#report tr:odd").addClass("odd"); $("#report tr:not(.odd)").hide(); $("#report tr:first-child").show(); $("#report tr.odd").click(function(){ $(this).next("tr").toggle(); $(this).find(".arrow").toggleClass("up"); }); });  '; echo '
A B C D E
United States of America 306,939,000 9,826,630 km2 English

Additional information



'; ?>

和HTML文件,

  //--------------------------------------------------------------------------------------index.html------------------------------------------------------------------------------------     function loadXMLDoc(){ var xmlhttp; if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else{ // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getData.php",true); xmlhttp.send(); }   

Let AJAX change this text

php文件在html表单中加载时按预期加载,但是使用ajax加载表的切换函数不起作用。 如何在ajax中完成这项工作?

尝试使用附加到表父级的委托处理程序替换您的单击处理程序。

 $("#report").delegate("tr.odd", "click", function() { $(this).next("tr").toggle(); $(this).find(".arrow").toggleClass("up"); }); 

由于表捕获了click事件,因此单击新的(替换的)元素将按预期工作,因为事件从目标元素冒泡到处理程序所连接的父级。 只有当第一个参数中传递给选择器的元素与.delegate匹配时,处理程序才会执行传递的函数。

编辑:jQuery 1.3.2没有.delegate ,但你可以使用.live代替:

 $("#report tr.odd").live("click", function() { $(this).next("tr").toggle(); $(this).find(".arrow").toggleClass("up"); }); 

要重新应用CSS,您可以执行以下操作:

 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("myDiv").innerHTML = xmlhttp.responseText; $("#report tr:odd").addClass("odd"); $("#report tr:not(.odd)").hide(); $("#report tr:first-child").show(); } 

或者删除那个长ajax方法并根据@Tieson T的建议使用$.load .load:

 $("#changeContent").click"(function() { $("#myDiv").load("getData.php", function() { $("#report tr:odd").addClass("odd"); $("#report tr:not(.odd)").hide(); $("#report tr:first-child").show(); }); }); 

并确保将您的按钮更改为此按钮以用于上述解决方案。

  

使用.live满足要求=>

 $("#btnSubmit").live("click", myValidation,submitAction); 

toogleFunction围绕文档准备好,当文档加载时,浏览器会触发此事件。

在执行Ajax请求时,您实际上是从服务器获取字符串并更改div的内容。

您需要做的是将函数放在主页面中,并在更改页面内容后将函数附加到新元素的click事件。

希望这可以帮助。

所以你正在使用jQuery,但是你编写自己的加载器? 呵呵。

如果您打算通过Ajax加载表,只需使用.load():

 function loadReportTable(){ $('myDiv').load('getData.php'); } 

您还需要使用上面@ karim79提供的代码段,因为新内容的事件处理程序将无法使用正常的.click()语法正确绑定。