Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 查找父元素数据值并显示它_Javascript_Jquery_Html_Graph - Fatal编程技术网

Javascript 查找父元素数据值并显示它

Javascript 查找父元素数据值并显示它,javascript,jquery,html,graph,Javascript,Jquery,Html,Graph,我制作了一个简单的水平图表,并使用jQuery和html中的数据值来设置每个条的宽度,这部分工作正常。我一直试图在每个图形栏中显示数据值。下面的jQuery代码显示最后一个图形栏的数据值,在每个图形栏中为22%。如何正确显示每个图形栏的数据值 HTML代码 <div class="graph-bar-bg"> <span class="graph-bar" data-value="78"><i></i></span> </di

我制作了一个简单的水平图表,并使用jQuery和html中的数据值来设置每个条的宽度,这部分工作正常。我一直试图在每个图形栏中显示数据值。下面的jQuery代码显示最后一个图形栏的数据值,在每个图形栏中为22%。如何正确显示每个图形栏的数据值

HTML代码

<div class="graph-bar-bg">
  <span class="graph-bar" data-value="78"><i></i></span>
</div> 

谢谢您的帮助。

从您的代码中,我得到的是每个图形栏中只有一个I标记,因此循环通过I标记不是您所需要的。设置css后,只需在一行中正常执行即可

$(document).ready(function() {
     $('.graph-bar').each(function() {    
          var barWidth = $(this).data('value');    
          $(this).css("width", barWidth + "%");
          $(this).find('i').text(barwidth);     
     });
});
试试这个

$(document).ready(function() {
  $('.graph-bar').each(function() { 
      var barWidth = $(this).data('value');  
      $(this).css("width", barWidth + "%");
      $(this).children().text(barWidth);     
  });
});

下面是fiddle中的工作示例,您希望生成以下运行结果:

代码:
$(文档).ready(函数(){
$('.graph bar')。每个(函数(){
var barWidth=$(this.data('value');
if(parseInt(barWidth,10)<40){
$(this.addClass('lt');
}else if(parseInt(barWidth,10)<60){
$(this.addClass('md');
}否则{
$(this.addClass('gt');
}
$(this.css(“宽度”,barWidth+“%”);
$(this.find('i').text(barWidth);
});
});
。图形条bg{
背景色:#bdd;
填充:4px10px;
位置:相对位置;
}
.图形栏{
显示:块;
宽度:6px;
背景色:红色;
边缘底部:6px;
}
中尉{
背景色:#1EAB15;
}
医学博士{
背景色:#A9AB15;
}
.gt{
背景色:#D81C1C;
}

用html()替换它。希望它有用。谢谢詹!非常感谢与parseInt相关的额外代码行,它非常有用。
$(document).ready(function() {
  $('.graph-bar').each(function() { 
      var barWidth = $(this).data('value');  
      $(this).css("width", barWidth + "%");
      $(this).children().text(barWidth);     
  });
});