Javascript 继承此函数以发挥作用
我想通过使用在单击时运行的函数来更改它,以便更清楚地编写它。这是一个有效的代码:Javascript 继承此函数以发挥作用,javascript,jquery,this,Javascript,Jquery,This,我想通过使用在单击时运行的函数来更改它,以便更清楚地编写它。这是一个有效的代码: menuHamburger.click(function () { if($(this).hasClass("closed")){ $(this).removeClass("closed"); }; subMenu.removeClass("show"); if (mainSidebar.toggleClass('a
menuHamburger.click(function () {
if($(this).hasClass("closed")){
$(this).removeClass("closed");
};
subMenu.removeClass("show");
if (mainSidebar.toggleClass('active')) {
return true;
}
});
我想这样写:
menuHamburger.click(function () {
closedHamburderOnClick();
if($(this).hasClass("closed")){
$(this).removeClass("closed");
};
subMenu.removeClass("show");
if (mainSidebar.toggleClass('active')) {
return true;
}
});
function closedHamburderOnClick(){
if($(this).hasClass("closed")){
$(this).removeClass("closed");
};
}
但它不起作用。如何修复它?在这种特殊情况下,只需将
$(this)
传递到函数中,并声明要使用的参数:
menuHamburger.click(function () {
closedHamburderOnClick($(this));
// (removed lines here I'm fairly sure you meant to remove in the question)
subMenu.removeClass("show");
if (mainSidebar.toggleClass('active')) {
return true;
}
});
function closedHamburderOnClick(elements){
if(elements.hasClass("closed")){ // You can get rid of this entirely
elements.removeClass("closed");
} // No ; after the block attached to control flow statements
}
如果您出于某种原因需要呼叫ClosedHamburderOn单击
,以便此
中的内容与您呼叫时的内容相同,您可以使用:
然后在其中使用此
:
function closedHamburderOnClick(){
if($(this).hasClass("closed")){ // You can get rid of this entirely
$(this).removeClass("closed");
} // No ; after the block attached to control flow statements
}
还有一个函数也以相同的方式处理this
,但是call
和apply
处理参数的方式不同
但是在这种情况下,不需要调用
或应用。您可以像其他任何函数一样将$(this)
作为函数参数传递。您不必测试元素是否有类来移除它。只需执行$(this.removeClass(“closedshow”)代码>告诉我在你的第二个代码块中有几行你想删除。@DenysSéguret,我不认为OP的重点是hasClass
Hamburder…嗯。我现在饿极了!
function closedHamburderOnClick(){
if($(this).hasClass("closed")){ // You can get rid of this entirely
$(this).removeClass("closed");
} // No ; after the block attached to control flow statements
}