Eva*_*van 13 html javascript jquery jquery-plugins
我有一部分代码通过AJAX调用动态加载,方法是将结果附加到父元素,类似于:
<div class="parent">
<!-- Inner content loaded dynamically -->
<div class="child">
</div>
<div class="child">
</div>
<!-- ... -->
</div>
Run Code Online (Sandbox Code Playgroud)
现在,为了挂钩鼠标悬停事件,我会做这样的事情:
$(".parent").on("mouseenter", ".child", function(){
//Do fun stuff here
}
$(".parent").on("mouseleave", ".child", function(){
//Undo fun stuff here
}
Run Code Online (Sandbox Code Playgroud)
这对标准函数来说效果很好,但是我想将它附加到第三方插件(在我的例子中,HoverIntent,但实际上是任何插件) -
附加HoverIntent插件的语法如下:
$(".child").hoverIntent( makeTall, makeShort )
Run Code Online (Sandbox Code Playgroud)
...但我希望这适用于我最初加载文档时不可用的动态内容,而这$(".parent").on("hoverIntent", ".child", function(){});似乎不是正确的方法.
将插件应用于初始化后加载的元素的正确方法是什么$(document).ready()?
jer*_*mel 11
jquery .on通过监视父对象上的事件,然后在事件源自匹配的子选择器时调用处理程序来工作.但是,在您的情况下,您要监视的事件是元素已更改
浏览器仅为输入元素触发onchange事件(因为它们可以由用户更改).
如果任何其他元素发生变化,则必须是因为javascript,因此您可以在创建新内容后调用函数.
$(".child", parentElementContext).hoverIntent( makeTall, makeShort )
Run Code Online (Sandbox Code Playgroud)
有两个实用的解决方案
1)我通常做的是创建一个采用上下文(如文档)的init方法.
MyPage.init = function(context) {
$('.selector', context).hoverIntent();
$('.other', context).dialog(); // any other plugins
};
Run Code Online (Sandbox Code Playgroud)
然后我在更新DOM时手动调用init(因为我在更新dom时总是不需要调用init)
$.ajax({
url: url,
data: data,
success: function(data){
var context = $('.parent');
context.html(data);
MyPage.init(context); //calls hoverIntent and other plugins
}
});
Run Code Online (Sandbox Code Playgroud)
2)如果你真的需要监控一切,你可以使用这个插件 http://james.padolsey.com/javascript/monitoring-dom-properties/
然后 $('.parent').on('valuechange', function() { /* init plugins*/}