How to access data attribute using jQuery

I struggle with what is probably a very simple jQuery bit

I have html like this:

<div class="star-rating" data-star-rating="5.0"></div> <div class="star-rating" data-star-rating="2.0"></div> 

I have javascript that should do something based on the star rating of each of these elements, and currently looks like this:

 $('.star-rating').jRate({ startColor : '#ccc', endColor : '#ccc', readOnly : true, rating : <value of data-star-rating> }); 

I want to replace <value of data-star-rating> with the value of the data attribute related to the item being processed

I thought this would work $(this).data('starRating') , but that doesn't look like

How can I access the value of the data attribute in this situation?

+5
source share
5 answers

$(this) does not apply to the element on which the jRate function is jRate .

You can use a selector if there is only one element having this class

 $('.star-rating').jRate({ startColor : '#ccc', endColor : '#ccc', readOnly : true, rating : $('.star-rating').data('star-rating') }); 

For multiple items:

Iterate over all elements that have a star-rating class and bind the jRate plugin individually using the rating value of the corresponding element.

 $('.star-rating').each(function () { $(this).jRate({ startColor: '#ccc', endColor: '#ccc', readOnly: true, rating: $(this).data('star-rating') }); }); 

JSFiddle Demo I did not find the CDN link of this plugin, so the added mini-code in the JavaScript panel itself

+4
source

You can also use this:

 $(this).data('star-rating'); 

EDIT

Having read the question again. The comments are right, you have to .star-rating over the .star-rating array in order to apply jRate to each element, sorry for my misunderstanding.

 $('.star-rating').each(function () { $(this).jRate({ startColor: '#ccc', endColor: '#ccc', readOnly: true, rating: $(this).data('star-rating') }); }); 
+5
source

Since there are several elements that have a star-rating class, so you will need to scroll through the elements, and the forEach loop will make the current iteration element available in the loop so that you can use this element. And apply JRate.

  $('.star-rating').forEach(function(dateRating){ $(dateRating).jRate({ startColor : '#ccc', endColor : '#ccc', readOnly : true, rating : $(dateRating).attr("data-star-rating") }); }); 
+2
source

You should use this:

 $(this).attr('data-star-rating'); 
+1
source

$(this).data('star-rating') will work if you return it from a function.

 $('.star-rating').jRate({ startColor : '#ccc', endColor : '#ccc', readOnly : true, rating : function () { return $(this).data('star-rating'); } }); 
0
source

Source: https://habr.com/ru/post/1245314/


All Articles