什么是jQuery相当于"这"在JS?

时间:2014-08-16 10:17:55

标签: javascript jquery

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

编辑:我们说我有以下代码

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

jQuery相当于"这个"我可以使用而不是"这个"?

我希望这更清楚。

3 个答案:

答案 0 :(得分:1)

这是$(this)

$('.class').each(function(){
    $(this).css('color', 'red');
});

请在此处查看:http://jsfiddle.net/qrzpk5wv/

答案 1 :(得分:1)

在您的代码中

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;
});

答案 2 :(得分:0)

.each()中,回调函数接收当前索引和元素作为参数,因此您可以使用元素参数而不是this

$('#id').each(function(index, element) {
    var id = element.id;
    // or:
    var id = $(element).attr('id');
});