此关键字不返回 html 元素


const buttons = document.querySelectorAll(".btn");
buttons.forEach((btn) => {
btn.addEventListener("click", (e) => {
const btnHref = btn.getAttribute('href'); <==== works fine
const btnHref = this.getAttribute('href'); <==== does not work
const section = document.querySelector(btnHref);
const { left, top } = section.getBoundingClientRect();
window.scrollTo({
left: left + window.scrollX,
top: top + window.scrollY,
behavior: "smooth",
});

e.preventDefault();
});
});

我想,每当我们使用addEventListener并在回调内部时,'this'关键字都会被=到HTML元素,但在我的情况下,它不起作用,有人能告诉我为什么吗?我在jquery中也遇到了类似的问题,当一些人使用";这个";关键字好吧,我就是做不到,因为它不起作用。

在箭头函数中,如果您写:e.target.getAttribute('href');,它应该工作

使用normal function关键字而不是箭头函数。

btn.addEventListener("click", function (e){
// this...
});

最新更新