在回调函数中将 THIS 对象作为 jQuery 选择器传递
Passing THIS Object as an jQuery Selector in Callback Function
我正在努力实现这样的目标:
function theMain (sel,call) {
var el = $(sel) ;
// Some processes etc...
call("done") ;
}
theMain("div a",function(state){
if (state == "done") {
// Want "THIS" to be an DOM object,
// But it refers WINDOW object...
$(this).css("border","1px solid red") ;
}
}) ;
jQuery 以某种方式做到了,但是怎么做到的?
还是我必须那样做:
function theMain (sel,call) {
var el = $(sel) ;
// Some processes etc...
call(el,"done") ;
}
theMain("div a",function(that,state){
if (state == "done") {
that.css("border","1px solid red") ;
}
}) ;
有什么建议吗?
您需要使用 call
来执行此操作。
见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
function theMain (sel,callback)
{
var $sel = $(sel);
callback.call($sel, "done")
}
theMain("div a",function(state)
{
if (state == "done")
{
// this now refers to the jquery object (as above in $sel)
this.css("border","1px solid red") ;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href="#" >hello</a>
</div>
我正在努力实现这样的目标:
function theMain (sel,call) {
var el = $(sel) ;
// Some processes etc...
call("done") ;
}
theMain("div a",function(state){
if (state == "done") {
// Want "THIS" to be an DOM object,
// But it refers WINDOW object...
$(this).css("border","1px solid red") ;
}
}) ;
jQuery 以某种方式做到了,但是怎么做到的?
还是我必须那样做:
function theMain (sel,call) {
var el = $(sel) ;
// Some processes etc...
call(el,"done") ;
}
theMain("div a",function(that,state){
if (state == "done") {
that.css("border","1px solid red") ;
}
}) ;
有什么建议吗?
您需要使用 call
来执行此操作。
见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
function theMain (sel,callback)
{
var $sel = $(sel);
callback.call($sel, "done")
}
theMain("div a",function(state)
{
if (state == "done")
{
// this now refers to the jquery object (as above in $sel)
this.css("border","1px solid red") ;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href="#" >hello</a>
</div>