我有一个带有 div 标签的页面,我使用 jQuery .load() 加载不同的 View
<div class="main-content">
<div id="load"></div>
</div>
当我像下面这样加载不同的 View 时,我无法访问 settings.html 中的任何元素
$("#settings").click(function(){
$("#load").load("main/settings.html");
//not working
$("#test1").click(function(){
alert('hello');
});
});
根据this中的第二个答案帖子:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call...
所以我将我的 .click()
代码移动到正在加载的页面(在本例中为 settings.html),我可以访问 settings.html 中的元素。或者我可以执行发布的建议的类似代码
$("#settings").click(function(){
$("#load").load("main/settings.html", function(){
$("#test1").click(function(){
alert('hello');
});
});
});
//or
$("#settings").click(function(){
$("#load").load("main/settings.html");
$(document).on("click","#test1",function(event){
alert('hello');
});
});
但我想知道如何绑定(bind)所有元素,假设我提前不知道哪些元素。在上面的示例中,我知道我需要绑定(bind) #test1
id。但是如果我有一个像 play.js
这样的文件,我在其中更改了加载页面上的不同内容,上面列出的方法将要求我将我的代码与 play.js
分开> 并将每一部分放入与加载事件相关的函数中。我有很多 .load()
事件,想将我的 js 像 .click()
等保存在一个单独的文件中。
如何在没有提前指定的情况下绑定(bind)加载的所有元素?或者我如何告诉 jQuery 执行类似的操作:
$("#settings").click(function(){
$("#load").load("main/settings.html", function(){
// pseudo code
(function(){
bind all elements from main/settings.html to DOM
});
});
});
所以像这样在它后面列出的脚本可以访问这些元素。
<script src="../js/play.js"></script>
最佳答案
这里的其他答案都是很好的解决方案,但是我想解释一下发生这种情况的实际原因:load
是一个异步 函数,这意味着它不是做一些工作并在完成后返回,而是安排要完成的工作然后立即返回。
在这种情况下,调用load
意味着最终 main/settings.html
的内容将被获取并放入 #load
,但不是在它运行之后的代码行。因此,您无法选择尚未创建的元素。
为了管理这种编程风格,此类函数通常接受一个回调
作为参数,这是另一个函数(由您,用户提供),稍后将在操作时由 API 调用已完成。在本例中,它是 load
的第二个参数。在此函数中,您可以根据操作的结果进行操作。
关于jquery - 从使用 jQuery .load() 加载的页面访问 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38936793/