问题
When I write jQuery code, I use $(this)
to change element:
$('.classname').click(function(){
$(this).toggleClass('collapsed');
// ..
});
Now I have are javascript class, looks like this:
class CabinetFormSize {
constructor() {
this.cabinetBTN = $(".cabinetBTN");
this.events();
}
events() {
this.cabinetBTN.click(this.toggleMenu.bind(this));
}
toggleMenu() {
console.log($(this));
this.cabinetBTN.toggleClass('d-none');
}
}
If i write this in toggleMenu()
I have class instance, but I need the element.
console.log($(this))
How can I use $(this)
in toggleMenu()
function to take element?
If i delete bind(this)
, console.log($(this))
work, but in this string this.cabinetBTN.toggleClass('d-none')
i have Uncaught TypeError: Cannot read property 'toggleClass' of undefined
.
回答1:
Don't bind any this
to your callback. jQuery will call your callback with the correct this
. Like
this.cabinetBTN.click(this.toggleMenu);
When you bind this
to a function, you're basically creating a new function with a "hard-coded" this
value.
My solution with a working snippet:
class CabinetFormSize {
constructor() {
this.cabinetBTN = $(".cabinetBTN");
this.events();
}
events() {
this.cabinetBTN.click(this.toggleMenu);
}
toggleMenu() {
console.log($(this).text())
}
}
new CabinetFormSize();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cabinetBTN">Click me</div>
来源:https://stackoverflow.com/questions/55236604/how-use-jquery-this-in-javascript-classes