使用Ajax加载数据不会让我添加JavaScript事件
问题描述:
今天,当使用JQuery库中的$ .ajax方法并从基于PHP的页面加载数据时,我发现尝试附加某些事件时出现问题。使用Ajax加载数据不会让我添加JavaScript事件
我有一个html文件这样的:
<html>
<script src="/public_html/assets/js/jquery/jquery-3.2.1.min.js"></script>
.container {
display: block;
width: 500px;
height: 500px;
background: red;
}
<!-- Here goes the container -->
<div class='wrapper'></div>
<script>
$(document).ready(function() {
$(".container").on("contextmenu", function (event) {
event.preventDefault();
alert("It works.");
});
$.post("example.php", function(result) {
$(".wrapper").html(result);
});
});
</script>
凡在页面的末端有Ajax请求到PHP文件:
echo "<div class='container'>";echo "</div>";
当请求结束时,容器出现,但当试图进行调整时,它不起作用。但是,如果它是通过原始html完成的,它就可以工作。任何解决这个问题的方法?
答
使用event delegation如果具有.className
"container"
元件后document
DOMContentLoaded
或window
load
事件
$(function() {
$(document).on("contextmenu", ".container", function(event) {
// do stuff
})
})
使用'$(函数(){})'附加到
document
? – guest271314似乎不工作。 – Weyooo
您是否将所有代码都包含在'$(function(){})'中?什么是'$(“”)。html(result);'? – guest271314