gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:51:36 24 4
gpt4 key购买 nike

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

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>

关于javascript - 在回调函数中将 THIS 对象作为 jQuery 选择器传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42680909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com