[英]jQuery's selector is undefined when using webpack
I was learning webpack and had created a module to do a simple task: click an element to add this css property on it margin-right: 5rem;
我正在学习webpack,并创建了一个模块来完成一个简单的任务:单击一个元素,在其
margin-right: 5rem;
添加此CSS属性margin-right: 5rem;
import $ from 'jquery'
class ShiftRight {
constructor() {
this.more = $('.more')
this.shifting()
}
shifting() {
this.more.click(function() {
this.more.addClass('more--clicked')
})
}
}
export default ShiftRight
HTML's part is simple too: HTML的部分也很简单:
<div class="more">
<div class="more-sign"></div>
</div>
The error message: Cannot read property 'addClass' of undefined
. 错误消息:
Cannot read property 'addClass' of undefined
。 How come this.more
is undefined? 为什么
this.more
是不确定的? Is that because of jQuery? 那是因为jQuery吗? What's the pure JavaScript way to cooperate with webpack in this case?
在这种情况下与webpack合作的纯JavaScript方法是什么?
jQuery seems to be loaded because you get an error on this.mode.addClass
not on $(".mode")
or this.more.click
. jQuery似乎已加载,因为在
this.mode.addClass
而不是$(".mode")
或this.more.click
。
The problem is the context, inside the click callback function, this
doesn't refer to the ShiftRight
instance, it refers to the clicked element. 问题是情况下,点击回调函数内,
this
并不指ShiftRight
例如,它指的是点击的元素。 Using $(this).addClass("more--clicked")
使用
$(this).addClass("more--clicked")
shifting() {
this.more.click(function() {
$(this).addClass('more--clicked')
})
}
or an arrow function 或箭头功能
shifting() {
this.more.click(() => {
this.more.addClass('more--clicked')
})
}
should fix that 应该解决
if it is a jquery problem try to add this to your webpack config 如果是jquery问题,请尝试将其添加到您的webpack配置中
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.