获取子项 div 数据属性的高度,然后设置父项的高度
Get the Height of a child div data attribute and then set the Height of the Parent
html 看起来像这样。
<div id="carousel4up">
<div class="owl-carousel" data-composer='carousel4up' data-config='{
"height" : 350, "other": false }'
...
</div>
</div>
高度是从数据配置文件中设置的,它可能会发生变化。我想根据 class="owl-carousel"
数据配置键值对高度的值设置 id="carousel4up"
高度。
这是我的开始js
var owlHeight = $(".owl-carousel").attr(data-config);
$("#carousel4up").height(owlHeight);
虽然我不知道如何通过数组定位并获取高度值。
改变这个
var owlHeight = $(".owl-carousel").attr(data-config);
至此
var owlHeight = $(".owl-carousel").data('config');
//or .attr('data-config');
一个问题,需要有单引号:
data-config='{"height" : 350, "other": false }';
要将属性变成一个 JS 数组,这样做:
var owlHeight = $.parseJSON($(".owl-carousel").attr('data-config'));
//or the non-jQuery version JSON.parse($(".owl-carousel").attr('data-config'));
然后这样称呼它:
$("#carousel4up").height(owlHeight['height']);
JSFiddle Demo
如果您提供的数据是 JSON 格式,那么您可以这样做:
// Use attr if you expect the data-config value to change in javascript
// Otherwise use .data()
var config = $("#carousel4up .owl-carousel").attr("data-config");
// JSON.parse converts json string to javascript object
var height = JSON.parse(config).height;
$("#carousel4up").css("height", height + "px");
#carousel4up {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="carousel4up">
<div class="owl-carousel" data-composer="carousel4up" data-config='{"height" : 350, "other": false }'>
I am big, yay!
</div>
</div>
html 看起来像这样。
<div id="carousel4up">
<div class="owl-carousel" data-composer='carousel4up' data-config='{
"height" : 350, "other": false }'
...
</div>
</div>
高度是从数据配置文件中设置的,它可能会发生变化。我想根据 class="owl-carousel"
数据配置键值对高度的值设置 id="carousel4up"
高度。
这是我的开始js
var owlHeight = $(".owl-carousel").attr(data-config);
$("#carousel4up").height(owlHeight);
虽然我不知道如何通过数组定位并获取高度值。
改变这个
var owlHeight = $(".owl-carousel").attr(data-config);
至此
var owlHeight = $(".owl-carousel").data('config');
//or .attr('data-config');
一个问题,需要有单引号:
data-config='{"height" : 350, "other": false }';
要将属性变成一个 JS 数组,这样做:
var owlHeight = $.parseJSON($(".owl-carousel").attr('data-config'));
//or the non-jQuery version JSON.parse($(".owl-carousel").attr('data-config'));
然后这样称呼它:
$("#carousel4up").height(owlHeight['height']);
JSFiddle Demo
如果您提供的数据是 JSON 格式,那么您可以这样做:
// Use attr if you expect the data-config value to change in javascript
// Otherwise use .data()
var config = $("#carousel4up .owl-carousel").attr("data-config");
// JSON.parse converts json string to javascript object
var height = JSON.parse(config).height;
$("#carousel4up").css("height", height + "px");
#carousel4up {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="carousel4up">
<div class="owl-carousel" data-composer="carousel4up" data-config='{"height" : 350, "other": false }'>
I am big, yay!
</div>
</div>