我正在尝试使用 on
事件。代码
$(".draggable").on("mouseover", function () {
if (!$(this).data("init")) {
$(this).data("init", true).draggable();
}
});
但是上面的代码不起作用。可拖动插件不适用于元素。现在,如果我用 live
替换 on
事件,那么它就开始工作。代码
$(".draggable").live("mouseover", function () {
if (!$(this).data("init")) {
$(this).data("init", true).draggable();
}
});
有人可以解释一下我做错了什么吗?
最佳答案
如果 .live()
有效,那么这可能意味着代码运行时您正在操作的元素不存在。
这要么意味着您在运行代码之前没有等待 DOM 准备就绪,要么您需要使用 .on
的委托(delegate)版本。
$(function() {
$(document).on("mouseover", ".draggable", function () {
if (!$(this).data("init")) {
$(this).data("init", true).draggable();
}
});
});
您应该将 document
替换为包含所有 .draggable
元素的最深嵌套容器的选择器。
关于javascript - 如何在事件中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12725462/