0

I tried to build up a simple star rate render function by github.com/wbotelhos/raty. It would transfer the "scores" of data attributes to stars.

HTML

<div class="score_show" data-scores="4"></div>
<div class="score_show" data-scores="2"></div>

JS

Method1 failed

$('.score_show').raty({ readOnly: true,score: $(this).data('scores')});

The method failed,so I try another method.

Method2 works

  $('.score_show').each(function(){
   var score=$(this).data('scores');
   $(this).raty({ readOnly: true,score: score});
  })

I thought the problem in method1 is that the $(this) did not represent for the correct element.But could someone give me an more detailed explain about the reason method1 failed? Thanks.

user2837851
  • 1,151
  • 3
  • 15
  • 20

3 Answers3

3

In javascript, $(this) means nothing but a method call - it calls a method named $() and passes the object referred by the keyword this.

When you talk about in the context of jQuery, $ refers to the jQuery library and that method returns a jQuery object which refers to the dom elements referred by the argument passed.

In your case you want to get the data-score values from the score_show objects... so first you need to get a reference to those objects to fetch the data value.

In your first sample, this might be referring different object(we can't say much about it without knowing where it is placed and how that script is invoked)

But in your second sample you are calling $('.score_show') which will return a jQuery object which contains all the elements with the class score_show and when you use .each() it iterates through each of those elements and calls the callback method passed to .each(). Inside the each callback this refers to the dom element which is currently being iterated through so you can get the data-score attribute of that element by using $(this).data('scores')

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

in you case ,$(this) means current looping div object..you can use console.log($(this)) to see what it is..

Raymond Cheng
  • 2,425
  • 21
  • 34
0

this in javascript usually refer to the object that invoked the current function.

Inside the .each(), this represents the current iterated DOM object

$(this) is just used to wraps the DOMElement in a jQuery object so you can apply jQuery method on this.

Felix
  • 37,892
  • 8
  • 43
  • 55