简体   繁体   English

jquery在加载html之前执行

[英]jquery executes before html is loaded

How to make the html load before javascript function如何在javascript函数之前加载html

 $(document).ready(function() { var x = 10; if(x == 10) { $('h1').text("Its changed !"); alert("Test"); } })
 <h1>Hello</h1>

Here the alert message will popup,这里会弹出警告消息,

I also tried,我也试过,

 $(function(){ window.on('load',function(){ //code }) })

but it doesn't work.但它不起作用。

做你想做的基本方法是在body标签末尾的html代码末尾添加脚本。

Your second code snippet should only be :你的第二个代码片段应该只是:

window.onload = function(){
    /*some code*/
}

The problem appears to be that javascript does not wait for .text() to finish before continuing.问题似乎是 javascript 在继续之前不等待 .text() 完成。 Alert then fires, which freezes the browser, preventing text() from completing.然后触发警报,冻结浏览器,阻止 text() 完成。 There are a couple of ways around this.有几种方法可以解决这个问题。 You could avoid calling functions that freeze the browser (like alert()) or set a timeout before calling alert, like so:您可以避免调用冻结浏览器的函数(如 alert())或在调用 alert 之前设置超时,如下所示:

setTimeout(function(){alert('Test')},20);

The timeout will allow time for the previous execution to finish before calling the code within the function.超时将允许在调用函数内的代码之前完成前一次执行的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM