[英]What is the jQuery equivalent of “this” in JS?
按照标题,$('#id')是否与此相同,例如在每个循环中?
编辑:假设我有以下代码
$('#id').each(function() {
var id = $(this).attr('id');
});
我可以使用什么等效于“ this”的jQuery代替“ this”?
我希望这更清楚。
这是$(this)
:
$('.class').each(function(){
$(this).css('color', 'red');
});
在这里查看: http : //jsfiddle.net/qrzpk5wv/
在你的代码中
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;
});
在.each()
回调函数接收当前指数与元素作为参数,所以你可以使用元素的说法,而不是this
:
$('#id').each(function(index, element) {
var id = element.id;
// or:
var id = $(element).attr('id');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.