gpt4 book ai didi

javascript - 通过 Ajax 调用另一个页面期间 Jquery 未运行

转载 作者:行者123 更新时间:2023-11-28 00:49:06 24 4
gpt4 key购买 nike

我有索引页面,从索引页面我调用了 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>

最佳答案

  1. 您正在使用 jQuery,但您忘记将其包含在您的 index.php 中:

    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="script/javaScript.js"></script>
  2. 当您使用 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" );
    });
    });
  3. one.php 中删除额外的元素(htmlheadscript)文件:

    <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>
  4. 如果您使用 jQuery,就像您所做的那样,使用 $.ajax 发送 Ajax 请求。 .

关于javascript - 通过 Ajax 调用另一个页面期间 Jquery 未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com