Javascript jQuery的等价物是什么;这";在JS中?
根据标题,$('#id')是否与此相同,例如在一个each循环中 编辑:假设我有以下代码Javascript jQuery的等价物是什么;这";在JS中?,javascript,jquery,Javascript,Jquery,根据标题,$('#id')是否与此相同,例如在一个each循环中 编辑:假设我有以下代码 $('#id').each(function() { var id = $(this).attr('id'); }); 我可以用什么jQuery等价于“this”而不是“this” 我希望这更清楚。在.each()中,回调函数接收当前索引和元素作为参数,因此您可以使用元素参数而不是此: $('#id').each(function(index, element) { var id
$('#id').each(function() {
var id = $(this).attr('id');
});
我可以用什么jQuery等价于“this”而不是“this”
我希望这更清楚。在.each()
中,回调函数接收当前索引和元素作为参数,因此您可以使用元素参数而不是此
:
$('#id').each(function(index, element) {
var id = element.id;
// or:
var id = $(element).attr('id');
});
这是$(这个)
:
请参见此处:在您的代码中
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;
});
我不知道如何更好地解释我知道你的问题是什么吗?或者显示您的代码并解释itI会认为jQuery不是JavaScript,但它使用JavaScript。JavaScript是一种语言,jQuery是一个用JavaScript编写的库。至于最初的问题,您需要更清楚地了解您所问的问题,也许可以编写一个代码示例?是否有可能不使用“this”?您可以使用标准循环和索引。但是为什么要避免
$(this)
?我试图理解什么是“this”,以及它在jQuery中的等价物是什么。没有找到解决某个特定问题的方法我明白了。。。在上面的例子中,$(this)
是$('.class').eq(0)
,然后是$('.class').eq(1)
,等等。。。范围更改是由jQuery完成的,我认为您需要深入研究它们的源代码以发现更多细节。@AdrienHingert您到底想做什么<代码>此是此
;它不会因为您正在使用jQuery而变得无效。在他添加示例之前,我已经回答了这个问题。我重写了我的答案来反映这一点。
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;
});