有人可以解释为什么会这样。这是在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);
答案 0 :(得分:2)
如果我正确地阅读HTML5 Drag and drop,dataTransfer
对象仅在拖放期间与“拖动数据存储”相关联,有时它被解除关联或禁用,实际上表示items
为空。
因此,event.dataTransfer
只能在ondrop
处理程序中使用,如果您需要保留超出您需要复制它们的项目(尽管我不确定复制项目会按预期工作,您可能需要立即提取所需的数据。)
答案 1 :(得分:0)
你的问题接缝是,当setTimeout计时器运行时,调用你的函数的this
将不会是this
,这将是window
因此你需要如果您想要正确的行为,请更改它:
取自here使用此覆盖全局覆盖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);
...
希望有所帮助