我正在更新问题。为了简化情况,我将这个脚本放在 index.php 文件
中<form name="f" action="index.php" method="post">
<input type="button" name="but" id="but" value="Retrieve">
<div id="div"></div>
<input type="submit" name="ok">
</form>
<script type="text/javascript">
document.getElementById("but").onclick = function(){
var http = false;
if (window.XMLHttpRequest){
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHttp");
}
if (http){
http.open("POST","other.php",true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(){
if (http.status==200 && http.readyState==4){
document.getElementById("div").innerHTML = http.responseText;
}
};
http.send(null);
}
};
document.getElementById("y").onclick = function(){
alert("okaaay");
};
</script>
并且有other.php文件和下面的脚本
<?php
echo "<input type='text' name='y' id='y'>";
?>
Ajax 脚本工作得很好,但我的问题是当在 index.php 页面中检索到这个标记的输入元素时,使用第二个 JavaScript 代码我无法操作它,请帮忙,谢谢 :)
最佳答案
更改代码,以便在 other.php 返回响应后设置“y”onclick,如下所示:
http.onreadystatechange = function(){
if (http.status==200 && http.readyState==4){
document.getElementById("div").innerHTML = http.responseText;
document.getElementById("y").onclick = function(){
alert("okaaay");
};
}
};
否则,您将在尚不存在的元素上设置该事件处理程序:-)
关于php - ajax 代码中的 Javascript 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11696289/