What's the best way to store multiple values for jQuery's $.data()?

前端 未结 3 1117
南笙
南笙 2021-01-04 09:08

If storing multiple (10+) values on a large number of divs, is it more optimal to store them all in a single object, or as separate values?

Single Object:

3条回答
  •  礼貌的吻别
    2021-01-04 09:50

    In 1.4 you can do this:

    $('#somediv').data({ one : 1, two : 2, three : 3 });
    

    This is a great way to initialize the data object. HOWEVER, in 1.4.2, bear in mind that using this form will REPLACE ANY existing data on this element. So, if you try this:

    $('#somediv').data( 'one', 1 );
    
    $('#somediv').data({ two : 2, three : 3 });
    

    You will be blowing away the value for 'one'.

    (On a personal note, I think it is a shame since jQuery already makes extensive use of merging objects with its $.extend. Its not clear to me why that wasn't used here.)

    UPDATE (suggested by user: @ricka, thank you):

    1.4.3 and on, it merges the data (http://api.jquery.com/data/#data-obj):

    In jQuery 1.4.3 setting an element's data object with .data(obj) extends the data previously stored with that element. jQuery itself uses the .data() method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

    Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object. If you are using third-party plugins it may not be advisable to completely replace the element's data object, since plugins may have also set data.

提交回复
热议问题