我正在尝试使用on
事件。代码
$(".draggable").on("mouseover", function () {
if (!$(this).data("init")) {
$(this).data("init", true).draggable();
}
});
但上面的代码不起作用。可拖动插件不适用于元素。现在,如果我用on
替换live
事件,那么它就会开始工作。代码
$(".draggable").live("mouseover", function () {
if (!$(this).data("init")) {
$(this).data("init", true).draggable();
}
});
任何人都能解释我的错误吗?
答案 0 :(得分:3)
如果.live()
有效,则可能意味着代码运行时您操作的元素不存在。
这意味着您在运行代码之前不等待DOM准备就绪,或者您需要使用.on
的委派版本。
$(function() {
$(document).on("mouseover", ".draggable", function () {
if (!$(this).data("init")) {
$(this).data("init", true).draggable();
}
});
});
您应该使用包含所有document
元素的最深嵌套容器的选择器替换.draggable
。
答案 1 :(得分:2)
它取决于您使用的jquery版本
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
请参阅此link了解详情