数据属性刷新画布

Data attribute refresh canvas

本文关键字:刷新 数据属性      更新时间:2023-09-26

我有一个通过数据百分比绘制的圆形。如果90%,它将绘制形状的90%。

我的想法是每秒钟删除这个正方形的1%,问题是设置数据属性不起作用,如果我通过DOM进行设置,形状就不会自我更新。

$(document).ready(function() {    
    var charta = $(".chart");
var value = charta.data("percent");
charta.data("percent", "200");
<div class="chart" data-percent="90"></div>

当数据属性发生变化时,没有触发的事件

因此,将data-percent属性从90更改为200总是不会引起注意。

您可以创建一个自定义jQuery事件,在更改data-percent时触发该事件。。。

// tell the .chart class to listen for a custom event
// called "changedDataAttribute"
$('.chart').on('changedDataAttribute', function(e){    
    // call a function to redraw the chart
    redrawMyChart(this.id,$(this).data('percent'));
});

// chain jquery commands to first change data-percent to 200
// and then trigger the custom "changedDataAttribute" event
$('.chart').data("percent",200).trigger('changedDataAttribute'); 

// redraw the chart with id==chartId
function redrawMyChart(chartId,newPercent){
    // now redraw your chart with id==chartId at newPercent
}

。。。但是,除非出于某种原因需要事件层,否则没有必要添加它

相反,只要更改data-percent,就可以直接调用redrawMyChart

// redraw the chart with id==chartId
function redrawMyChart(chartId,newPercent){
    // now redraw at newPercent
}