在动态加载的内容中执行JS
我已经开始开发一个动态加载所有不同页面内容的项目。
从表面上看,这似乎很简单,对脚本的 AJAX 调用返回放置在 DIV 内的内容。只不过不仅返回 HTML,还返回 JS。我看到很多这样的东西:-
<img src="spacer.gif" height="1" width="1" onload="SOMEJSHERE"/>
点缀在执行 JS 函数的代码中。这不提供我喜欢使用 JQuery 的那种 HTML/JS 代码分离。
我可以理解他们不想一次加载所有 JS 和 HTML,数量太多了...但这感觉不是最好的方法。
请问有什么经验和建议吗?
莱尔
I've started working on a project that loads all of the different pages content dynamically.
On the surface this seems simple enough, an AJAX call to a script that returns the content that is placed inside a DIV. Except that not only HTML but JS is returned as well. I'm seeing a lot of things like this:-
<img src="spacer.gif" height="1" width="1" onload="SOMEJSHERE"/>
Dotted in the code to execute JS functions. This doesn't provide the kind of HTML/JS code separation I've come to love using JQuery.
I can understand that they don't want to load all the JS and HTML at once, there is an awful lot of it... But this just doesn't feel like the best way.
Some experience and suggestions please?
Lyle
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看 jQuery .live() 事件。它可以将行为(事件绑定)应用于页面上与给定选择器匹配的所有当前和未来元素。
这意味着您新加载的 HTML 不需要包含任何脚本。只需确保加载的元素具有正确的选择器(类名和 ID)。
Have a look at the jQuery .live() event. It can apply behaviors (event bindings) to all current and future elements on the page, which match the given selectors.
This means that your newly-loaded HTML need not contain any script. Just make sure the loaded elements have the right selectors (class names and id's).
嘿我使用“eval”动态执行js。
例如
hey i use "eval" to execute js dynamically.
e.g.
最后,我使用了 JQuery UI 中的 tabs.select 选项(我们用于 ajaxed 页面)并根据需要执行适当的 JS。
In the end I used the tabs.select option from JQuery UI (which we were using for the ajaxed pages) and executed the appropriate JS as needed.