![](/img/trans.png)
[英]JS/jQuery - Better to run event handler in $(document).ready or in called function
[英]Run jquery code in angularJS app document ready event
我试图在angular应用程序中运行一些jquery代码,我试图运行的代码涉及到钩住一些选择器/
$(document).ready(function () {
Configuration.anchorToUseForMainSearch = $("#header_element")
}
由于尚未加载DOM,因此该选择器返回“ length:0”,还有其他事件我应该使用吗?
尝试使用此:
angular.element(document).ready(function () {
// Your document is ready, place your code here
});
但这是相同的结果。
您可以为此创建一个指令并设置执行代码的超时时间。
我要说的是,您走错了路。 Angular方式将避免使用jQuery。 如果绝对需要,我建议您将其放在附加到主模块的.run()中。 我希望此功能可以触发时,文档已“准备就绪”。
angular.module('myApp', [])
.run(function myAppRunFn() {
// commit sins here.
});
var target = $("#wrapperDiv")[0]; //or document.body when you not sure // create an observer instance var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if($(mutation.addedNodes).filter('#header_element').length) { //code for what you want here console.log("Item added to DOM"); } }); }); // configuration of the observer: var config = { attributes: true, childList: true, characterData: true, subtree: true }; // pass in the target node, as well as the observer options observer.observe(target, config); setTimeout(function(){ console.log('Adding Element from some other code'); $("#innerDiv").append("<div id='header_element'>"); }, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrapperDiv"> <div id="innerDiv"> </div> <div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.