最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set DIV height for each by it's data-attribute - Stack Overflow

programmeradmin0浏览0评论

I am trying to loop through over each div that has a class of block and set it's height individually based on it's data-attribute data-height

HTML

<div class="block" data-height="300"></div>
<div class="block" data-height="500"></div>
<div class="block" data-height="700"></div>

jQuery

$('.block').each(function(){ 
    var size = $this.attr('data-height');
    $(this).height(size);
});

JS Fiddle /

It's not returning the height when I have it in the each method though thus not setting the height for each one.

I am trying to loop through over each div that has a class of block and set it's height individually based on it's data-attribute data-height

HTML

<div class="block" data-height="300"></div>
<div class="block" data-height="500"></div>
<div class="block" data-height="700"></div>

jQuery

$('.block').each(function(){ 
    var size = $this.attr('data-height');
    $(this).height(size);
});

JS Fiddle http://jsfiddle/MLnBY/166/

It's not returning the height when I have it in the each method though thus not setting the height for each one.

Share Improve this question asked Mar 28, 2015 at 14:34 MyojiMyoji 2794 silver badges13 bronze badges 4
  • 1 data-* attributes can be also accessed by doing .data('height');. – D4V1D Commented Mar 28, 2015 at 14:37
  • @D4V the way OP is doing it is still valid. – nicael Commented Mar 28, 2015 at 14:37
  • 1 I know, I never said it was invalid. Just pointing that out :) – D4V1D Commented Mar 28, 2015 at 14:38
  • $(this).data("height") – Smile0ff Commented Mar 28, 2015 at 14:43
Add a ment  | 

3 Answers 3

Reset to default 5

The problem is in $this; replace it with $(this)

var size = $(this).attr('data-height');

You forgot the () on the second line of JS at $(this)

Hey you can do it using pure javascript like this:

var size = this.getAttribute('data-height');
发布评论

评论列表(0)

  1. 暂无评论