Javascript 使用;这";另一个,外部功能
我想使用jQuery的多个选择器,在它们上设置Javascript 使用;这";另一个,外部功能,javascript,jquery,Javascript,Jquery,我想使用jQuery的多个选择器,在它们上设置on(),然后使用“$(this)”实现我需要的东西。这应该是这样的: $(".one, .two, .three").on("someEvent", function () { $(this).something; }); 但是,我想移动$(这个)到它自己的函数,类似于: function outSideFunction() { $(this).something; } $(".one, .two, .three").on("someEv
on()
,然后使用“$(this)
”实现我需要的东西。这应该是这样的:
$(".one, .two, .three").on("someEvent", function () {
$(this).something;
});
但是,我想移动$(这个)代码>到它自己的函数,类似于:
function outSideFunction() {
$(this).something;
}
$(".one, .two, .three").on("someEvent", function () {
outSideFunction();
});
但正如你可能理解的那样,这并没有真正起作用。是否有一些解决方法,以便我仍然可以在外部函数中使用this
?只需传递回调函数名,然后在函数中自由使用$(this)
function outSideFunction() {
$(this).css({color: "red"}); // for example
}
$(".one, .two, .three").on("someEvent", outSideFunction);
以下是一些其他方法:
绑定
此
作为参数
美元代理
您可以将此
绑定到一个值:
function outSideFunction() {
$(this).something;
}
$(".one, .two, .three").on("click", function () {
outSideFunction.bind(this)();
});
例如:
函数外部函数(){
$(this.remove();
}
$(.1、.2、.3”)。在(“单击”,函数(){
绑定(这个)();
});代码>
单击以删除。
如果我正确理解了您的意思,您想保存此状态吗?如果是这样,只需将其存储在var中,如:“var self=this;”,然后使用self绑定
,jQuery中的代码>绑定是什么。他们非常不同。此方法确实具有某些功能,例如,如果要在希望访问此
的位置执行设置间隔
。谢谢。这也是一个有价值的答案:)
function outSideFunction( that ) {
$(that).css({color: "red"});
}
$(".one, .two, .three").on("click", function() {
outSideFunction(this);
// Other stuff here
});
function outSideFunction() {
$(this).css({color: "red"});
}
$(".one, .two, .three").on("click", $.proxy(outSideFunction, this.selector));
function outSideFunction() {
$(this).something;
}
$(".one, .two, .three").on("click", function () {
outSideFunction.bind(this)();
});