event currentTarget changes after setTimeout

后端 未结 4 1733
南方客
南方客 2021-01-04 19:06

consider:



        
4条回答
  •  Happy的楠姐
    2021-01-04 19:21

    event.currentTarget and some other properties change after exiting the event handler.

    Doing a context switch (setTimeout(... ,0);) in an event handler is common, it seems that the only way to correctly pass the event including currentTarget etc is to clone it as below.

    Note that this is only 'good enough' ... the clone is not exactly the original event, and it's context is different ... doing for example clone.stopPropogation() is meaningless ...

    If you need to change currentTarget etc on the clone delete !d.writable || !d.configurable || !d.enumerable ||

    let sel=document.getElementById('mys');
    
    function cloneEvent(e) {
    	function ClonedEvent() {};
    	let clone=new ClonedEvent();
    	for (let p in e) {
    		let d=Object.getOwnPropertyDescriptor(e, p);
    		if (d && (!d.writable || !d.configurable || !d.enumerable || d.get || d.set)) {
    			Object.defineProperty(clone, p, d);
    		}
    		else {
    			clone[p] = e[p];
    		}  
    	}
    	Object.setPrototypeOf(clone, e);
    	return clone;
    }
    
    sel.onchange=function(e) {
    	console.log(e.currentTarget);
    	let clone=cloneEvent(e);
    	setTimeout(e => {
    		console.log(e.currentTarget);
    	}, 0, clone);
    }

提交回复
热议问题