Which jQuery method is better: “.attr('data-thing');” or “.data('thing');”

前端 未结 2 1785
自闭症患者
自闭症患者 2020-12-22 06:26

Which one is better:

$(\'div\').attr(\'data-stuff\');

or

$(\'div\').data(\'stuff\');

After having a discu

2条回答
  •  别那么骄傲
    2020-12-22 07:16

    Taking what all people have said into consideration, here is "the answer":

    .data is better because:

    1. it's slightly shorter to type.
    2. It can protect you from possible future changes to data structure (although unlikely).

    .attr is better because:

    1. it loads nearly 3 times faster.

    I think I will continue using .attr myself, but thank you all for this information :)

提交回复
热议问题