[英]How to execute a function in javascript after an html element is loaded via AJAX without jQuery?
I need to execute a given javascript function after a part of the page is loaded via AJAX. 通过AJAX加载页面的一部分后,我需要执行给定的javascript函数。 I have no control over how the page loads so trigerring an event from the page is not an option, I suppose I'll need to check the body for the element I need and execute after this element is exists.
我无法控制页面的加载方式,因此无法触发页面中的事件,我想我需要检查主体以查找所需的元素,然后在该元素存在后执行。
I saw that I could do this using jQuery ".on" method, but my jQuery version is from before this feature was introduced so I can't use it. 我看到可以使用jQuery“ .on”方法执行此操作,但是我的jQuery版本是在引入此功能之前的版本,因此我无法使用它。 What's the best way to do this using no third-party libraries?
不使用第三方库执行此操作的最佳方法是什么?
Here's an example using jQuery: 这是使用jQuery的示例:
//bind to the body a "load" handler for elements that have class names of "hello"
$('body').on('load','.hello',function(){
alert("Hello is fully loaded, proceed with your program logic");
})
PS: related question that I've read before posting this one. PS:发布此问题之前,我已经阅读了相关问题。 How to bind a function to Element loaded via Ajax
如何将函数绑定到通过Ajax加载的Element
You can create a function to call when the elements are loaded, and another function to check if they are loaded at an interval. 您可以创建一个函数,以在元素加载时调用,还可以创建另一个函数以检查是否以一定间隔加载元素。 Then attach the load checking function to the body's
onload
attribute. 然后将负载检查功能附加到主体的
onload
属性。 For example: 例如:
<body onload="checkLoaded()">
<script type="text/javascript">
var afterLoaded = function() {
// code to execute once elements are in place
console.log("Elements loaded.");
};
var checkLoaded = function() {
var interval = setInterval(function() {
if(document.getElementsByClassName("hello").length) {
clearInterval(interval);
afterLoaded();
}
}, 1000);
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.