JavaScript:使用引用函数时在偶数处理程序中获取$(this)
我对JavaScript的理解有问题。我想转换以下工作代码:JavaScript:使用引用函数时在偶数处理程序中获取$(this),javascript,Javascript,我对JavaScript的理解有问题。我想转换以下工作代码: button.addEventListener('click', function(e) { console.log($(this)); // w.fn.init [div... (lots of stuff here) ); 转换为: button.addEventListener('click', handleButtonClick(e) ); function handleButtonClick (e) { co
button.addEventListener('click', function(e) {
console.log($(this)); // w.fn.init [div... (lots of stuff here)
);
转换为:
button.addEventListener('click', handleButtonClick(e) );
function handleButtonClick (e) {
console.log(e) // MouseEvent {isTrusted: true, screenX: 1418, screenY: 295, clientX: 683, clientY: 151, …}
}
如何使用引用的函数从转换版本中的原始代码中获取
$(this)
?我尝试过使用bind
,但它不起作用,很可能是因为我做得不对。您正在调用该函数并将其返回值(在上述情况下为未定义的
)传递给eventlistener。您只需传递变量而不调用它
您可以使用e.target
或this
button.addEventListener('click', handleButtonClick );
function handleButtonClick (e) {
console.log(e.target) // MouseEvent {isTrusted: true, screenX: 1418, screenY: 295, clientX: 683, clientY: 151, …}
}
谢谢,是的,我必须执行console.log($(e.target))来完全复制原始代码的功能。当创建这个最小的示例时,
把手按钮点击之后的(e)
。