问题
is it possible to trigger a 'change' on the select element of the amcharts multiple data set chart that they have provided.?
$(".amChartsDataSetSelector").find("select").val("2").trigger("change");
This is the code i tried,what it does basically is change the select option to the one i have selected ,but it doesn't change the chart accordingly.
Is there any other alternatives to this method?
Here's my fiddle:
Here's the original link to the chart on amcharts.
回答1:
The jQuery .trigger( works only when events are bound using jQuery .on function (or any event binding function). Below is a simple example to show you what was happening.
Jump to #Solution below to skip this demo.
$(function() {
var el = document.getElementById('checkEvent');
if (el.addEventListener) {
el.addEventListener("change", checkEvent, false);
} else {
el.attachEvent('change', checkEvent);
}
function checkEvent() {
alert('Event Check');
}
$('#changeDDValue').click(function() {
$('#checkEvent').val("2").change();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="checkEvent" style="width: 180px;">
<option value="0">first data set</option>
<option value="1">second data set</option>
<option value="2">third data set</option>
<option value="3">fourth data set</option>
</select>
<button id="changeDDValue">Change DataSet</button>
Solution:
Added a button #change
to set a different dataset like below,
$('#change').click(function () {
var selectEl = $(".amChartsDataSetSelector").find("select").val("2").get(0);
fireEvent.call(selectEl, 'change');
});
And then use fireEvent function below to trigger the change event instead of trigger('change')
,
//http://stackoverflow.com/a/2490876/297641
function fireEvent(eventName) {
var event; // The custom event that will be created
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
if (document.createEvent) {
this.dispatchEvent(event);
} else {
this.fireEvent("on" + event.eventType, event);
}
}
Fixed jsFiddle
来源:https://stackoverflow.com/questions/26562276/trigger-change-on-selecting-dataset-amcharts-multiple-data-sets-chart