0

当用户选择一行并将其放在 jquery 网格之外时,我试图获取一个事件。这是网格内发生拖放的拖放功能,效果非常好 -

    $(".grid-canvas")
        .on("drop", function (e, dd) {
              // somecode
                    });

我正在尝试跟踪在网格画布 div 之外“任何地方”发生的拖放。但反向选择似乎不起作用。我试过这个,但没有工作 -

$(".grid-canvas")
    .not(this)
    .on("drop", function (e, dd) {
     alert("outside");
 });

我试过这个,但它也会触发网格内的拖放 -

$(":not(.grid-canvas)")
                               .on("drop", function (e, dd) {
                                alert("outside");
                            });

任何帮助表示赞赏。谢谢。

4

2 回答 2

0

直接定位文档以获取所有drop,然后过滤掉嵌套在.grid-canvas自己内部的任何内容(可能比伪选择器更有效):

$(document).on('drop', function(e, dd) {
    if ( ! $(e.target).closest('.grid-canvas').length ) {
        // dropped outside
    }
});
于 2013-08-12T22:36:38.940 回答
0

首先,阅读“on”文档,以便您更好地理解。您的第二个示例说明了以下内容:

Select all elements with the "grid-canvas" class
  ...that aren't `this`
  ...and watch for drop events on them, and do this when they happen

这显然不是你想要的。第二个更接近:

Select all elements that don't have a grid-canvas class
  ...and watch for drop events on them, and do this when they happen

哪个更接近,但是a)向页面中的几乎每个元素添加事件侦听器,这是一个非常糟糕的主意,并且b)仍然会触发您的网格画布div中的元素这就是您所看到的,因为您仍然将听众附加到他们身上。

您可能想要做的是:

Select a high-level element (e.g. `body`)
  ...listen for a drop event, and check if the drop event happened on .grid-canvas or one of its children

这看起来像:

$('body').on('drop', function(evt) {
  //Check if the element dropped on has a .grid-canvas as a parent
  if($(evt.target).parents('.grid-canvas').length == 0) {
    alert('Outside');
  }
}

有几种方法可以检查目标是否在 .grid-canvas 中,我使用的只是一个示例。例如,您也可以这样做$('.grid-canvas').has(evt.target)-从相反的方向着手,这可能更有意义,具体取决于您的想法。

但总的来说:jQuery 不是英文的,你不能只是将听起来像是应该做你想做的事情的命令串在一起。确保您阅读了您正在使用的函数并了解它们的作用,您将更快地建立您的 jQuery 技能。

于 2013-08-12T22:43:02.330 回答