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;
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:
<div class="more">
<div class="more-sign"></div>
</div>
The error message: Cannot read property 'addClass' of undefined
. How come this.more
is undefined? Is that because of jQuery? What's the pure JavaScript way to cooperate with webpack in this case?
jQuery seems to be loaded because you get an error on this.mode.addClass
not on $(".mode")
or 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. Using $(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
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.