在回调函数中将此对象作为jQuery选择器传递

时间:2017-03-08 20:04:55

标签: javascript jquery pass-by-reference

我正在努力实现这样的目标:

specify 'success' do
  expect{ logger.info('title', message) }.to output(expected).to_stdout
end

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

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您需要使用call来执行此操作。

请参阅https://stackoverflow.com/a/6995286/1834561

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>