HTML data and a string that looks like a number

前端 未结 3 1302
梦如初夏
梦如初夏 2021-01-19 04:48

For this html

this js:

console.log($(\'div\').data(\'a\'));

retur

相关标签:
3条回答
  • 2021-01-19 05:23

    Yep, use:

    console.log($('div').attr('data-a'));
    
    0 讨论(0)
  • 2021-01-19 05:38

    From the jQuery doco on .data():

    Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

    So you need to say:

    console.log($('div').attr('data-a'));
    

    (Note that you specify the full attribute name, including the 'data-' prefix.)

    0 讨论(0)
  • 2021-01-19 05:42

    You can bypass data() and grab the attribute directly:

    console.log($('div').attr('data-a'));
    

    Demo

    0 讨论(0)
提交回复
热议问题