【问题标题】:Add data attiribute values as an inline-css "width" value将数据属性值添加为内联 CSS“宽度”值
【发布时间】:2017-01-30 16:02:31
【问题描述】:

我有这样的代码:

<span class="bar" data-percent="25,6"></span>
<span class="bar" data-percent="40,6"></span>
<span class="bar" data-percent="10,6"></span>
<span class="bar" data-percent="60"></span>

我想获取数据百分比值,将逗号更改为点并将此值作为宽度添加到跨度。

像这样:

<span class="bar" data-percent="25,6" style="width: 25.6%"></span>

$('span[class="bar"]').each(function(index, item) {
  var a = $(item).data('percent');
  a = a.replace(/,/g, '.') + '%';
  $(item).width(a);
});
.bar {
  height: 40px;
  background: red;
  display: block;
  margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="bar" data-percent="25,6">First Span</span>
<span class="bar" data-percent="40,6">Second Span</span>
<span class="bar" data-percent="10,6">Third Span</span>
<span class="bar" data-percent="60">Fourth Span</span>

我写了一些 jquery 但它不工作,如果数据中没有逗号,jquery 不工作。

https://jsfiddle.net/mod7910u/

感谢 Josh,这是最后一个工作和动画版本: https://jsfiddle.net/mg4p5bmc/1/

【问题讨论】:

    标签: javascript jquery html css custom-data-attribute


    【解决方案1】:

    问题是由于属性data-percent="60" 值被视为数字。而其他属性值由于存在逗号而被视为字符串。由于值 60 是一个数字,.replace() 方法会引发错误。

    要解决这个问题,只需在.replace() 之前调用.toString() 方法,以确保该值为字符串。

    Updated Example

    var a = $(item).data('percent');
    a = a.toString().replace(/,/g, '.') + '%';
    

    您也可以使用String() 构造函数将值转换为字符串:

    var a = $(item).data('percent');
    a = String(a).replace(/,/g, '.') + '%';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多