如何动态地包含一个包含javascript的html文件 [英] How to dynamically include a html file containing javascript
问题描述
在我的网站我有一个简单的导航栏,点击不同的项目导致主要内容改变。在技术上,所有这些都是在一个文件main.html中完成的,其中包含所有内容,我使用jquery函数load来动态加载其他html文件以将其放在main.html中。只要嵌入的这些html文件中没有javascript,这个工作很好。但是有一个我想要嵌入的文件,其中也有javascript代码,它应该在$(document).ready上执行。但是这不会发生 - 在javascript中没有错误,它只是永远不会被执行。我想这是因为我只是改变了main.html的DOM,然后就不会有onReady事件触发。有人可以给我一些了解什么是最好的方式来获得所需的行为?将javascript放在main.html中会导致事情发生,但这对我来说是没有选择的。
in my website i have a simple navigation bar where clicking on the different items causes the main content to change. Technically, all is done in a single file "main.html", which contains everything and i use the jquery function "load" to dynamically load other html files to place it inside the main.html. This works just fine as long as there is no javascript in these html files i embedded. But there is one file i want to embedd, which has also javascript code in it, which should get executed on $(document).ready. But this never happens - there is no error in the javascript, it just never gets executed. I suppose it's because i only change the DOM of the "main.html" and then there will be no "onReady" event fired. Can someone give me some idea of what would be the best way to get the desired behaviour? Placing the javascript in the "main.html" would cause things to work, but this is no option for me.
提前感谢
更新:解决问题
问题解决了。当我在onReady()事件之外调用javascript(如Loic Coenen所建议的),它的工作原理就如同。我也删除了包裹的标签。非常感谢所有帮助我的人!
update: problem solved Problem is solved. When i call the javascript outside the onReady() event (as Loic Coenen suggested), it works just as excpected. I also removed the tags wrapped around. Many thanks to all who helped me!
推荐答案
您可以触发自定义事件通知您的其他。 html
加载树的脚本。我没有尝试过,但我会使用这样的东西:
You can trigger a custom event to notify your other.html
script that the tree is loaded. I haven't tried it, but I would use something like that :
在main.html中:
$('#div_to_load').load('other.html',{},function(){
$('#div_to_load').trigger('loaded')
})
在other.html
$('#div_to_load').on('loaded', function(){
// Code to execute
})
我不知道是否可以做这个诀窍
I don't know if that could do the trick.
编辑:我认为直接包含在您的 other.html
中的JavaScript仍然被执行。
Edit : I asume that the javascript directly included in your other.html
is executed anyway.
这篇关于如何动态地包含一个包含javascript的html文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!