[英]Jquery not running during call to another page via Ajax
我有索引页面,从索引页面我称为Jquery和PHP页面(合并在one.php文件中),如果我单独运行one.php文件,一切运行正常,但是如果我通过Ajax调用同一页面,则它不会运行。
样例代码:
的index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mouseover demo</title>
<script src="script/javaScript.js"></script>
</head>
<body>
<a style="cursor:pointer;" onclick="addpage()">click</a>
<div id="view"></div>
</body>
</html>
javascript.js
$(document).ready(function () {
$( "div[class^=star]" ).mouseover(function() {
$( this ).find( "span" ).text( "mouse Over" );
}).mouseout(function() {
$( this ).find( "span" ).text( "mouse Out" );
});
});
function addpage(){
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("view").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","one.php",true);
xmlhttp.send();
}
one.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mouseover demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="script/javaScript.js"></script>
</head>
<body>
<table>
<tr>
<td>
<div class="staroverout">
<span>move cursor to change text</span>
</div>
<br>
<div class="staroverout">
<span>move cursor to change text</span>
</div>
<br>
<div class="nstaroverout">
<span>move cursor to change text</span>
</div>
</td>
</tr>
</table>
</body>
</html>
您正在使用jQuery,但忘记了将其包含在(在index.php
):
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="script/javaScript.js"></script>
使用Ajax获取数据时,应使用事件委托将事件附加到元素:
$(document).ready(function () { $('body').on('mouseover', "div[class^=star]", function() { $( this ).find( "span" ).text( "mouse Over" ); }).on('mouseout', "div[class^=star]", function() { $( this ).find( "span" ).text( "mouse Out" ); }); });
从one.php
文件中删除多余的元素( html
, head
, script
):
<table> <tr> <td> <div class="staroverout"> <span>move cursor to change text</span> </div> <br> <div class="staroverout"> <span>move cursor to change text</span> </div> <br> <div class="nstaroverout"> <span>move cursor to change text</span> </div> </td> </tr> </table>
如果您正在使用jQuery,则使用$.ajax
发送Ajax请求。
如果您尝试在one.php中删除那些jquery.js,该怎么办。
因为当您再次将其包含在页面“ one.php”中时,该jQuery已经包含在页面中一次,所以我又被包含了,这导致了JQuery Conflict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.