简体   繁体   中英

jQuery pass data-attribute to function

I use my HTML element to pass a data-attribute to jQuery but I can't seem to use that data-attribute as an option in the function:

Instead of

    var options1 = {
        series: [60, 10, 30],

I am trying to use

    <div id="evaluation" class="donut" data-series="60,10,30">

    autoValues = $('#evaluation').attr('data-series');
    const evaluation = [autoValues];

    var options1 = {
        series: evaluation,
        ...
</script>

This is returning a NaN error.

The attribute value is a string. You need to split the string and parse them to create a list of integers.

You can also use the .data() jQuery method to access data attributes.

 autoValues = $('#evaluation').data('series'); const evaluation = autoValues.split(',').map(Number); var options1 = { series: evaluation, }; console.log(options1);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="evaluation" class="donut" data-series="60,10,30">

Data attributes are strings so you'd have to convert that string to numbers.
jQuery's .data() can parse your data attributes to data types if you specify them as json

 const evaluation = $('#evaluation').data('series'); var options1 = { series: evaluation, } console.log(options1);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="evaluation" class="donut" data-series="[60,10,30]">

Data attributes are essentially just strings. As such, evaluation = [autoValues] is effectively the same as evaluation = ["60,10,30"] .

However , you may want to store JSON in your data attributes, because jQuery will automatically try to JSON.parse them for you if you use the data() function, ie $('#evaluation').data('series') .

 const options = { series: $('#evaluation').data('series') }; console.log(options);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="evaluation" class="donut" data-series="[60,10,30]">

With this approach, you could even store the entire options object in a single data attribute:

 const options = $('#evaluation').data('options'); console.log(options);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="evaluation" class="donut" data-options='{"series": [60,10,30]}'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM