簡體   English   中英

在回調函數中將此對象作為 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM