1

有人可以解释为什么会这样。这是在ondrop处理程序中

为什么它会在计时器内丢失它的值?

var _this = this;

this.event = event;

console.log(this.event.dataTransfer.items);
## DataTransferItemList {0: DataTransferItem, length: 1, item: function, clear: function, add: function}


setTimeout((function() {
  return console.log(_this.event.dataTransfer.items);
  ## DataTransferItemList {length: 0, item: function, clear: function, add: function}

}), 100);

即使这样也行不通:

var items, _items,
  _this = this;

items = event.dataTransfer.items;
_items = items;

setTimeout((function() {
  return console.log(_items);
}), 100);
4

2 回答 2

3

如果我正在正确阅读HTML5 拖放,则该dataTransfer对象仅在拖放期间与“拖动数据存储”相关联,其他时候它被取消关联或禁用,这实际上意味着它items是空的。

因此,event.dataTransfer只能在ondrop处理程序中使用,如果您需要保留项目之外的项目,则需要复制它们(虽然我不确定复制项目是否会按预期工作,但您可能需要提取所需的数据马上。)

于 2013-05-22T08:11:27.303 回答
0

那么您的问题接缝是当 setTimeout 计时器运行时this调用您的函数的函数将不一样,因此如果您想要正确的行为,您需要更改它:thiswindow

这里获取覆盖 setTimeout 和 setInterval 全局与此覆盖:

// Just place this lines in your javascript file
// Enable the passage of the 'this' object through the JavaScript timers
var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeST__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};

window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeSI__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};

然后您的功能将按预期工作:

...
console.log(this.event.dataTransfer);
## DataTransferItemList {0: DataTransferItem, length: 1, item: function, clear: function, add: function}

setTimeout((function() {
  return console.log(this.event.dataTransfer);
  ## DataTransferItemList {length: 0, item: function, clear: function, add: function}
}), 100);
...

希望能帮助到你

于 2013-05-22T07:42:45.880 回答