将外部html文件加载到div并使用其js函数

将外部html文件加载到div并使用其js函数

问题描述:

我有一些div:

<div id='dialog'></div>

现在,我想将一个外部html文件加载到该div中并使用其js函数.

Now I want to load into this div an external html file and use its js functions.

我知道我可以使用jQuery.Load()加载它,并且工作正常,问题是我想使用html js函数.

I know I can load it using jQuery.Load() and it works fine, the problem is that I want to use the html js functions.

主要问题是我有几个div,我将这个html文件加载到其中,并且我希望在激活js函数时,它只能在特定的div上工作.

The main problem is that I have several divs which I load this html file into them and I want that when I'm activating js function it will only work on the specific div.

我记得当发布jQuery1.4时我遇到了问题.在该版本中,.load()在指定目标容器后突然开始剥离js.

I remember I had the problem back when jQuery1.4 was issued. In that version, .load() suddendly began stripping out the js when a target container was specified.

我当时所做的事情:

  1. 将html和js分别放在不同的文件(例如 myhtml.html myjs.js )或视图中
  2. 让我的js文件充当js模块,并带有一个将jQuery元素作为参数的公共入口点功能(例如initContent)
  3. myhtml.html 中有一个不可见的链接,即<a href="myjs.js#initContent" class="dynamicJs" style="display:none;"></a>
  4. myhtml.html 加载到目标div后,在目标div中搜索$('a.dynamicJs')以提取js url,并从href
  5. 中输入入口点函数
  6. 如果以前未加载过js,则通过ajax调用将js动态加载到页面中
  7. 以目标div作为参数动态调用入口点函数
  1. separate html and js in different files (let's say myhtml.html and myjs.js ), or views
  2. have my js file act as a js module, with a public entry point function (say initContent) taking a jQuery element as a parameter
  3. have an invisible link in myhtml.html, namely <a href="myjs.js#initContent" class="dynamicJs" style="display:none;"></a>
  4. after loading myhtml.html into my target div, search for $('a.dynamicJs') in my target div to extract js url, and entry point function from the href
  5. if the js had not previously been loaded, dynamically load the js into the page trhough an ajax call
  6. dynamically call the entry point function with the target div as parameter

这也适用于CSS. 它需要一些时间才能在所有导航器上进行调整(IE上的css部分数量有限,以不同的方式动态调用函数),并且我得到的代码更多了.这也需要大量重构我的html/js模块(但我必须承认我结束了使用真正更干净的代码)

This also worked with css. It required some time to tweak it on all navigators (limited number of css sections on IE, different way to dynamically call a function), and I ended with much more code I expected in the first place. It also required a lot of refactoring of my html/js modules (but I must confess I ended having a code that was really cleaner)

我敢肯定,目前有一些框架可以更好地处理这种情况.但这就是我当时想出的.

I'm sure there are frameworks that handle this kind of situation way better by now. But this is what I came up with at that time.

希望这会有所帮助