这个问题让我抓狂......我正在通过Ajax调用PHP文件并将其解析为我的HTML内容。我必须这样做以获得动态内容,而不刷新页面。
我的问题是解析的代码不会执行任何jquery的东西。我需要一个Jquery滑块,例如在PHP文件中。但它被解析为普通的HTML,JQuery似乎无法识别它。
以下是一个示例:
HTML文件:
<html>
<head>
<script src="jquery-1.7.1" type="text/javascript"></script>
<script src="jscroller-0.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Add Scroller Object
$jScroller.add("#scroller_container","#scroller","right",1);
// Start Autoscroller
$jScroller.start();
});
</script>
<script type="text/javascript">
function showGet(str)
{
if (str=="")
{
document.getElementById("center").innerHTML="";
return;
}
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("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","content.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="content">
<input type="button" onclick="showGet(1)" value="showGet">
</div>
<div id="scroller_container">
<div id="scroller">
...[Content]...
</div>
</div>
</body>
</html>
这是content.PHP文件:
<?php
echo "
<div id=\"scroller_container\">
<div id=\"scroller\">
...[Content]...
</div>
</div>
"
?>
执行时,HTML有一个Button。如果单击该按钮,它会将content.php解析为<div id="content></div>
。
PHP包含与HTML相同的<div id="scroller" ....
。
HTML div工作,PHP文件中没有。为什么????我该如何让它发挥作用?
所有提示都提前许多!!
答案 0 :(得分:1)
使用jQuery ajax加载内容可以像使用load()方法一样简单:
/* loads a file into id=content and replaces exisitng html*/
$('#content').load( 'path/to/server/file', function(){
/* new content exists, intialize event handling
and plugins for new html here*/
})
答案 1 :(得分:0)
要获得动态添加的信息访问jQuery函数,您必须使用delegate()或on() -
http://api.jquery.com/on/ http://api.jquery.com/delegate/