“this"关键字不工作在jquery函数内

"this" keyword is not working inside jquery function

本文关键字:工作 jquery 函数 关键字 this quot      更新时间:2023-09-26

我想在我的jquery函数中使用"this"关键字,但它不适合我…

我试过以下方法:

1…不工作…

function getRequest() {
      var ReqPlace = $(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}

2 . .不工作…

var that=this;   //also tried var that=$(this);
function getRequest() {
      var ReqPlace = $(that).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}

3 . .工作,但这次我使用了一个按钮

<input type="button" onclick="getRequest(this);" />
function getRequest(that) {
      var ReqPlace = $(that).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}

上面的第三步工作得很好,但我不需要一个按钮是否有其他方法在函数

中使用"this"关键字

谢谢

this返回调用它的对象的实例。

在你的例子中,它不能在语句1中工作,因为由于某种原因,你调用了this并返回函数的实例,而不是这就是为什么它不能工作

同样适用于语句2考虑声明

var that = this;

如果这是在一个函数内这个将返回一个函数,这就是为什么它不工作。

最后,语句3工作的原因是它返回元素的html对象实例,因为该函数是元素的单击事件侦听器。注意,在函数中使用语句3调用this也可以工作。

你总是可以在函数中使用这个但是记住
$(query)
jQuery(query)

其中query是一个html对象或html字符串或css选择器字符串,将其与函数一起发送将导致错误。

如果你想在函数

中执行类似这样的代码
$(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');

除非这个是一个HTML对象,你应该做的是:

<div class='somedivinyourtemplate' id='hello'>
</div>
function () {
    $('#hello').parent('div.reqHere')
        .parent('div.allReqs').children('div.reqHere')
}

或者直接输入要选择的元素的id。

希望这能帮助你理解它是如何工作的

如果你想在jquery中使用"this"

给按钮id

<input type="button" id="getrequest" />
然后

 $("#getrequest").click(function(){
    $(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere')
    })