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

后端 未结 3 1366
终归单人心
终归单人心 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 01:57

    Storing property values directly on DOM elements is risky because of possible memory leaks. If you're using jQuery anyway, the .data() mechanism is a wonderful and safe way to keep track of per-element information. It allows for storage of arbitrary JavaScript data structures too, not just strings.

    edit — when your HTML markup contains data-foo attributes, those are implicitly read when the keys are accessed. That is, if your HTML looks like this:

    Then in jQuery:

    alert( $('#div1').data('purpose') ); // alerts "container"
    

    Furthermore, jQuery will also do some "smart" analysis of the attribute values. If a value looks like a number, jQuery will return a number, not a string. If it looks like JSON, it de-serializes the JSON for you.

    edit — here's a good trick: in the Chrome developer console (the "Console" view), you can type JavaScript expressions and have them evaluated. The evaluation is always done in the context of the page you're working on. If you select an element from the "Elements" view, then in the console the JavaScript symbol $0 will refer to that selected DOM element. Thus you can always inspect the "data" map for an element by going to the console and typing something like:

    $($0).data("something");
    

    The .data() function, if called with no parameters, returns all the key/value pairs:

    $($0).data();
    

提交回复
热议问题