Is there an advantage in how I store my data using jQuery?

后端 未结 3 1339
终归单人心
终归单人心 2021-01-27 01:36

I know understand more about how jQuery stores data.

Is there any advantage to doing one or the other of these:

$(\'#editCity\').data(\'href\', \"xx\");         


        
3条回答
  •  逝去的感伤
    2021-01-27 02:22

    They both have advantages... That said, 99% of the time you should be using .data('whatever', value)

    Advantages of using .data('whatever', value):

    • less apt to cause memory leaks because it's not using the DOM.
    • Slightly faster to pull data from memory than from the DOM.
    • Can put any type of object in it without serializing it to JSON first.

    Advantages of using .attr('data-whatever', value):

    • compatible with .data('whatever')
    • allows you to select the element by the value: $('[data-whatever=foo]')
    • You can put any object in it, but it will need to serialize if it's a complex type.

提交回复
热议问题