Creating a local reference to a jQuery.data key

前端 未结 2 679
别那么骄傲
别那么骄傲 2021-01-21 09:32

I\'m doing some testing on jQuery.data(), and I\'m trying to create a local reference to a certain data-key, which I hopefully can change locally and still affect \

2条回答
  •  不要未来只要你来
    2021-01-21 10:34

    If you store an object (or array) in .data() then you're actually storing a reference to it, so if you do:

    var obj = { key: 'value' }
    $(el).data('obj') = obj;
    obj.key = 'new value';
    

    $(el).data('obj').key will also be new value, because it's the same object.

    However if the value stored is a plain type instead (e.g. a number or a string) that a copy of it will be stored:

    var n = 5;
    $(el).data('obj') = n;
    n++;
    

    $(el).data('obj') will still be 5.

提交回复
热议问题