我试图在图库中添加 toggleImage 的功能并检查了 this线程和the code在其中一个答案中提供,但在控制台中得到 Uncaught TypeError: Cannot read property 'attr' of undefined
。
HTML:
<div id="gallery">
<figure>
<img data-src="/assets/images/small/one.jpg">
<a data-href="/assets/images/one.jpg">
</figure>
<figure>
<img data-src="/assets/images/small/two.jpg">
<a data-href="/assets/images/two.jpg">
</figure>
<figure>
<img data-src="/assets/images/small/three.jpg">
<a data-href="/assets/images/three.jpg">
</figure>
</div>
<div class="modal">
<div class="">
<img class="modal__image" src="">
</div>
<div class="modal__close">X</div>
</div>
有效的 JavaScript:
import $ from 'jquery'
class ToggleImage {
constructor() {
this.thumbnail = $('#gallery img')
this.modalImage = $('.modal__image')
this.passHref()
}
passHref() {
this.thumbnail.click(e => {
const href = $(e.target).siblings().attr('data-href')
this.modalImage.attr('src', href)
e.preventDefault
return false
})
}
}
const toggleImage = new ToggleImage()
如您所见,var href = $(this)
已更改为 $(e.target).siblings()
。在此更改之前,我尝试仅使用 this
或仅使用 e.target
与 getAttribute() 和非箭头函数,或添加 const that = this
在 const href
行之前并使用 that
代替,但它们都不起作用。我可以知道为什么吗?
并且,到目前为止,点击事件与操作代码捆绑在一起。但是因为我希望将操作与事件分开,$(e.target) 不适合这种情况。
class ToggleImage {
constructor() {
this.thumbnail = $('#gallery img')
this.modalImage = $('.modal__image')
this.passHref()
this.event() // added
}
event() {
this.thumbnail.click(this.passHref)
}
passHref() {
// some code other than $(e.target)...
}
}
最佳答案
在您的组件中,'this' 是'ToggleImage' 的对象。你不能使用 $(this) 因为这里 js 将 '$(this)' 理解为 '$(ToggleImage)'
关于javascript - ES6 模块中的 `this` 和 $(this) 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43499055/