鼠标悬停功能在 Chart.js 中表现异常
Mouse-over function behaving weird in Chart.js
1) 我有一个网站,用户可以在其中过滤下拉列表中的值,基于调用数据显示在图表上(使用 ChartJS)。
在此阶段,代码调用 JavaScript 函数,其中传入值(x、y 轴标签和值等)。然后,用户可以将鼠标悬停在图表上(来自 Chart.js 的内部函数调用)并在弹出窗口中获取值。
2) 然后,当用户从下拉列表中选择其他值,然后再次将鼠标悬停在坐标上以查看弹出值时,图形切换回旧数据(第一个下拉值 - 2019),直到几秒钟并改回其原始数据(当前从下拉列表传递 - 2020)。
问题 1. 即使我没有将旧数据保存在 JSON 或 cookie 或其他东西中,它如何能够传递旧数据。
注意: 我已经检查了我的 "console.log" 从下拉列表中传递的值是什么 -> 这是正确的.保留一个调试点,它告诉我正在传递给图形的当前数据集值 -> 这是正确的,没有传递两个数据集值。
问题2。这是Chart.JS插件的问题吗?因为我没有在我的 JS 中调用任何鼠标悬停事件。
如果是,我该如何解决?
问题 3。总的来说,这个问题的解决方案是什么?
以下是它的JS代码。
var initialize = function ()
{
canvas = document.getElementById('wo-chart');
searchBox = document.getElementById('wo-widget-search');
allTimeLabel = document.getElementById('wo-billed-total');
currentLabel = document.getElementById('wo-billed-current');
selectedDateLabel = document.getElementById('selected-wo-date');
selectedProblemLabel = document.getElementById('selected-wo-problem');
selectedTradeLabel = document.getElementById('selected-wo-trade');
dateSelectors = document.querySelectorAll('[data-wo-date]');
search();
// performs a new search when a different start date is selected
$(dateSelectors).click(function (event)
{
event.preventDefault();
console.log("Function Date Selectors Test! " + this.getAttribute('data-wo-date'));
selectedDateLabel.innerHTML = this.innerHTML;
selectedStartDate = this.getAttribute('data-wo-date');
search();
});
// performs a new search when a different problem is selected
};
return { initialize: initialize };
/**
* Performs a new search for WorkOrder chart data.
* @function
*/
function search()
{
otx.spinner(currentLabel, 'span');
otx.spinner(allTimeLabel, 'span');
var data = profile.getCurrentEntityInfoAsObject();
if (selectedStartDate !== null && selectedStartDate !== '')
{
data.rangeStartDate = selectedStartDate;
}
$.post('/Maintenance/MaintenanceWidget/GetWorkOrderChartData', data, function (result)
{
if (!result || result.DataSets.length < 2)
{
otx.alerts.error('We were unable to load Work Order chart data.');
return;
}
allTimeLabel.innerHTML = result.WorkOrdersAllTime;
currentLabel.innerHTML = result.WorkOrdersInPeriod;
$(canvas).siblings('iframe').remove();
workOrderChart = new Chart(canvas.getContext('2d'), {
type: 'line',
data: {
labels: result.Labels,
datasets: [
{
// ReSharper disable once PossiblyUnassignedProperty
label: result.DataSets[0].Label,
fill: true,
lineTension: 0.3,
backgroundColor: 'rgba(238,144,197,0.4)',
borderColor: 'rgba(238,144,197,1)',
borderWidth: 2,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'round',
pointBorderColor: 'rgba(238,144,197,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(238,144,197,1)',
pointHoverBorderColor: 'rgba(238,144,197,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
// ReSharper disable once PossiblyUnassignedProperty
data: result.DataSets[0].Data,
spanGaps: false
},
{
// ReSharper disable once PossiblyUnassignedProperty
label: result.DataSets[1].Label,
fill: true,
lineTension: 0.3,
backgroundColor: 'rgba(0,160,209,0.4)',
borderColor: 'rgba(0,160,209,1)',
borderWidth: 2,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'round',
pointBorderColor: 'rgba(0,160,209,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(0,160,209,1)',
pointHoverBorderColor: 'rgba(0,160,209,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
// ReSharper disable once PossiblyUnassignedProperty
data: result.DataSets[1].Data,
spanGaps: false
}
]
},
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
yAxes: [{ ticks: { beginAtZero: true } }]
}
}
});
result = null;
});
}})(jQuery, companyName, ProfileHelpers);
这是在 Chart.js:
下调用鼠标悬停功能的侦听器
function createEvent(type, chart, x, y, nativeEvent) {
return {
type: type,
chart: chart,
native: nativeEvent || null,
x: x !== undefined? x : null,
y: y !== undefined? y : null,
};
}
function fromNativeEvent(event, chart) {
var type = eventTypeMap[event.type] || event.type;
var pos = helpers.getRelativePosition(event, chart);
return createEvent(type, chart, pos.x, pos.y, event);
}
以下是.NET端的代码
public async Task<JsonResult> GetWorkOrderChartData(int targetId, TargetType targetType, int? problemId = null, DateTime? rangeStartDate = null, string search = null,
int? tradeId = null)
{
JsonResult result = await JsonValidateLoginAsync(ModuleClaimTypes.Maintenance).ConfigureAwait(false);
if (result != null)
{
return result;
}
try
{
// GetWorkOrderChartDataAsync calls a method in Service Class which extracts the data from DB according to the paramters passed.
return Json(await new MaintenanceWidgetReadService(DbContext, User)
.GetWorkOrderChartDataAsync(new TargetInfo(targetId, targetType), problemId, search, rangeStartDate, tradeId)
.ConfigureAwait(false));
}
catch (Exception ex)
{
await ex.LogAsync(HttpContext);
return Json(false);
}
}
解决了我的悬停问题。
这是由于另一个画布相互重叠而发生的。
必须删除旧的 canvas 并使用新的 canvas 重新加载部分内容。
这是我在 JS 中所做的参考。
$(dateSelectors).click(function (event)
{
event.preventDefault();
selectedDateLabel.innerHTML = this.innerHTML;
selectedStartDate = this.getAttribute('data-wo-date');
let canvas = $('#wo-chart');
canvas.remove();
$('#graph-container').append('<canvas id="wo-chart"></canvas>');
search();
});
1) 我有一个网站,用户可以在其中过滤下拉列表中的值,基于调用数据显示在图表上(使用 ChartJS)。
在此阶段,代码调用 JavaScript 函数,其中传入值(x、y 轴标签和值等)。然后,用户可以将鼠标悬停在图表上(来自 Chart.js 的内部函数调用)并在弹出窗口中获取值。
2) 然后,当用户从下拉列表中选择其他值,然后再次将鼠标悬停在坐标上以查看弹出值时,图形切换回旧数据(第一个下拉值 - 2019),直到几秒钟并改回其原始数据(当前从下拉列表传递 - 2020)。
问题 1. 即使我没有将旧数据保存在 JSON 或 cookie 或其他东西中,它如何能够传递旧数据。
注意: 我已经检查了我的 "console.log" 从下拉列表中传递的值是什么 -> 这是正确的.保留一个调试点,它告诉我正在传递给图形的当前数据集值 -> 这是正确的,没有传递两个数据集值。
问题2。这是Chart.JS插件的问题吗?因为我没有在我的 JS 中调用任何鼠标悬停事件。
如果是,我该如何解决?
问题 3。总的来说,这个问题的解决方案是什么?
以下是它的JS代码。
var initialize = function ()
{
canvas = document.getElementById('wo-chart');
searchBox = document.getElementById('wo-widget-search');
allTimeLabel = document.getElementById('wo-billed-total');
currentLabel = document.getElementById('wo-billed-current');
selectedDateLabel = document.getElementById('selected-wo-date');
selectedProblemLabel = document.getElementById('selected-wo-problem');
selectedTradeLabel = document.getElementById('selected-wo-trade');
dateSelectors = document.querySelectorAll('[data-wo-date]');
search();
// performs a new search when a different start date is selected
$(dateSelectors).click(function (event)
{
event.preventDefault();
console.log("Function Date Selectors Test! " + this.getAttribute('data-wo-date'));
selectedDateLabel.innerHTML = this.innerHTML;
selectedStartDate = this.getAttribute('data-wo-date');
search();
});
// performs a new search when a different problem is selected
};
return { initialize: initialize };
/**
* Performs a new search for WorkOrder chart data.
* @function
*/
function search()
{
otx.spinner(currentLabel, 'span');
otx.spinner(allTimeLabel, 'span');
var data = profile.getCurrentEntityInfoAsObject();
if (selectedStartDate !== null && selectedStartDate !== '')
{
data.rangeStartDate = selectedStartDate;
}
$.post('/Maintenance/MaintenanceWidget/GetWorkOrderChartData', data, function (result)
{
if (!result || result.DataSets.length < 2)
{
otx.alerts.error('We were unable to load Work Order chart data.');
return;
}
allTimeLabel.innerHTML = result.WorkOrdersAllTime;
currentLabel.innerHTML = result.WorkOrdersInPeriod;
$(canvas).siblings('iframe').remove();
workOrderChart = new Chart(canvas.getContext('2d'), {
type: 'line',
data: {
labels: result.Labels,
datasets: [
{
// ReSharper disable once PossiblyUnassignedProperty
label: result.DataSets[0].Label,
fill: true,
lineTension: 0.3,
backgroundColor: 'rgba(238,144,197,0.4)',
borderColor: 'rgba(238,144,197,1)',
borderWidth: 2,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'round',
pointBorderColor: 'rgba(238,144,197,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(238,144,197,1)',
pointHoverBorderColor: 'rgba(238,144,197,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
// ReSharper disable once PossiblyUnassignedProperty
data: result.DataSets[0].Data,
spanGaps: false
},
{
// ReSharper disable once PossiblyUnassignedProperty
label: result.DataSets[1].Label,
fill: true,
lineTension: 0.3,
backgroundColor: 'rgba(0,160,209,0.4)',
borderColor: 'rgba(0,160,209,1)',
borderWidth: 2,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'round',
pointBorderColor: 'rgba(0,160,209,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(0,160,209,1)',
pointHoverBorderColor: 'rgba(0,160,209,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
// ReSharper disable once PossiblyUnassignedProperty
data: result.DataSets[1].Data,
spanGaps: false
}
]
},
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
yAxes: [{ ticks: { beginAtZero: true } }]
}
}
});
result = null;
});
}})(jQuery, companyName, ProfileHelpers);
这是在 Chart.js:
下调用鼠标悬停功能的侦听器function createEvent(type, chart, x, y, nativeEvent) {
return {
type: type,
chart: chart,
native: nativeEvent || null,
x: x !== undefined? x : null,
y: y !== undefined? y : null,
};
}
function fromNativeEvent(event, chart) {
var type = eventTypeMap[event.type] || event.type;
var pos = helpers.getRelativePosition(event, chart);
return createEvent(type, chart, pos.x, pos.y, event);
}
以下是.NET端的代码
public async Task<JsonResult> GetWorkOrderChartData(int targetId, TargetType targetType, int? problemId = null, DateTime? rangeStartDate = null, string search = null,
int? tradeId = null)
{
JsonResult result = await JsonValidateLoginAsync(ModuleClaimTypes.Maintenance).ConfigureAwait(false);
if (result != null)
{
return result;
}
try
{
// GetWorkOrderChartDataAsync calls a method in Service Class which extracts the data from DB according to the paramters passed.
return Json(await new MaintenanceWidgetReadService(DbContext, User)
.GetWorkOrderChartDataAsync(new TargetInfo(targetId, targetType), problemId, search, rangeStartDate, tradeId)
.ConfigureAwait(false));
}
catch (Exception ex)
{
await ex.LogAsync(HttpContext);
return Json(false);
}
}
解决了我的悬停问题。 这是由于另一个画布相互重叠而发生的。
必须删除旧的 canvas 并使用新的 canvas 重新加载部分内容。
这是我在 JS 中所做的参考。
$(dateSelectors).click(function (event)
{
event.preventDefault();
selectedDateLabel.innerHTML = this.innerHTML;
selectedStartDate = this.getAttribute('data-wo-date');
let canvas = $('#wo-chart');
canvas.remove();
$('#graph-container').append('<canvas id="wo-chart"></canvas>');
search();
});