[英]How to make sure that the loaded file can be detected by a js code
I have this code in the file assets/URL.js
:我在文件
assets/URL.js
中有这段代码:
$(function(){
$("a").on("click", function () {
event.preventDefault();
var TheURL = $(this).attr('href');
if(TheURL){
$("#MyDiv").load(TheURL , { name: '' },
function() {
alert("done");
});
}
});
});
And what it does is that if an <a>
element is clicked, the function above prevents the page from going to that page then it gets the url and load it into the div
with the id MyDiv
.它的作用是,如果单击
<a>
元素,上面的 function 会阻止页面转到该页面,然后它会获取 url 并将其加载到具有 id MyDiv
的div
中。
Now this is the code of index.html
:现在这是
index.html
的代码:
<html>
<head>
<script type="text/javascript" src="assets/URL.js?v=1"></script>
</head>
<body>
<div id="MyDiv">
<a href="files/1.html"></a>
</div>
</body>
</html>
and the code of files/1.html
is: files/1.html
的代码为:
<a href="2.html">2</a>
now, when I click on <a>
in the file index.html
the content of the <div>
with the id MyDiv
changes the the content of file/1.html
without the page reloading.现在,当我单击文件
index.html
中的<a>
时,ID 为MyDiv
的<div>
的内容会更改file/1.html
的内容,而无需重新加载页面。
But when I click <a>
in the file file/1.html
the page reloads and goes to file/2.html
and doesn't follow the code in assets/URL.js
, how can I force it to follow it and just replace the content of the <div>
with the id MyDiv
?但是,当我在文件
file/1.html
中单击<a>
时,页面会重新加载并转到file/2.html
并且不遵循assets/URL.js
中的代码,我该如何强制它遵循它并且只是用 id MyDiv
替换<div>
的内容?
You need to setup the eventhandlers again when the dynamic html is loaded, right now you only bind the click event to the existing A tags in index.html, not the future ones in dynamic loaded content like 1.html加载动态 html 时,您需要再次设置事件处理程序,现在您只需将点击事件绑定到 index.html 中现有的 A 标签,而不是动态加载内容中的未来事件,如 1.ZFC35FDC70D5FC69D253EZAC788
You could try something like:您可以尝试以下方法:
$(function(){
RefreshEventHandlers();
});
function RefreshEventHandlers() {
$("a").on("click", function () {
event.preventDefault();
var TheURL = $(this).attr('href');
if(TheURL){
$("#MyDiv").load(TheURL , { name: '' },
function() {
alert("done");
RefreshEventHandlers(); // bind click to newly added A tags.
});
}
});
}
To make sure the click event handlers are set on all new A tags确保在所有新的 A 标记上设置单击事件处理程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.