我有索引页面,从索引页面我调用了 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 获取数据时,您应该使用 Event Delegation用于将事件附加到元素:
$(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 请求。 .
关于javascript - 通过 Ajax 调用另一个页面期间 Jquery 未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994112/