html看起来像这样。
<div id="carousel4up">
<div class="owl-carousel" data-composer='carousel4up' data-config='{
"height" : 350, "other": false }'
...
</div>
</div>
高度是从数据配置文件设置的,它可能会改变。我想根据id="carousel4up"
数据配置键值高度对的值设置class="owl-carousel"
高度。
这是我的开始js
var owlHeight = $(".owl-carousel").attr(data-config);
$("#carousel4up").height(owlHeight);
我不知道如何通过数组并找到获得高度的值。
答案 0 :(得分:3)
一个问题,你需要单引号:
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']);
答案 1 :(得分:1)
如果您提供的数据是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>
答案 2 :(得分:0)
更改此
var owlHeight = $(".owl-carousel").attr(data-config);
到这个
var owlHeight = $(".owl-carousel").data('config');
//or .attr('data-config');