2017-03-08 57 views
2

我想实现这样的事情:传递这个对象在回调函数jQuery选择

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") ; 
    } 
}) ; 

任何建议?

+1

这没有很大的意义。你试图达到什么目标? –

+0

我希望“THIS”是第一个代码中的一个DOM对象,但它指WINDOW对象@LeeTaylor – Digerkam

回答

1

您需要使用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>

+0

谢谢,非常感谢! – Digerkam

+0

@Anonymous是什么让你觉得呢?鉴于OP已经接受了答案......? –