gpt4 book ai didi

javascript - JS 中 "this"的 jQuery 等价物是什么?

转载 作者:行者123 更新时间:2023-12-02 17:04:54 25 4
gpt4 key购买 nike

根据标题,$('#id') 与此相同吗,例如在每个循环中?

编辑:假设我有以下代码

$('#id').each(function() {  
var id = $(this).attr('id');
});

我可以使用什么相当于“this”的 jQuery 来代替“this”?

我希望这更清楚。

最佳答案

在你的代码中

var $element = $('#id').each(function() {
// here this refers to the native JS element. The same object that you get when you call document.getElementById('id');
var id = this.getAttribute('id'); // this.id will also work

// $(this) refers to the jQuery collection object, which is same as $('#id').
var id = $(this).attr('id');

// A jQuery collection is also an array of native objects, so you can also access the element using array access
var id = $(this)[0].getAttribute('id');

// This may not make sense in the above example, but when you have the collection as a variable, this might be the best option
var id = $element[0].id;
});

关于javascript - JS 中 "this"的 jQuery 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25339180/

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