【问题标题】:Passing THIS Object as an jQuery Selector in Callback Function在回调函数中将此对象作为 jQuery 选择器传递
【发布时间】:2017-07-29 14:04:04
【问题描述】:

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

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

有什么建议吗?

【问题讨论】:

  • 这没有多大意义。你想达到什么目的?
  • 我希望“THIS”成为第一个代码中的 DOM 对象,但它引用了 WINDOW 对象@LeeTaylor

标签: javascript jquery pass-by-reference


【解决方案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>

【讨论】:

  • 谢谢,非常感谢!
  • @Anonymous 是什么让你这么认为?鉴于 OP 已经接受了答案...?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多