html & [removed] How to store data referring to html elements

前端 未结 8 1152
悲哀的现实
悲哀的现实 2020-12-31 15:29

I\'m working on a web application that uses ajax to communicate to the server. My specific situation is the following:

I have a list of users lined out in the html p

8条回答
  •  一向
    一向 (楼主)
    2020-12-31 15:50

    jQuery Data

    If you want to store custom data against a jQuery object, use the data function.

    $('#myField').data('name', 'Jack');
    var name = $('#myField').data('name');
    

    HTML5 data-* Attributes

    You can also use the HTML5 data-* attributes, though the APIs for accessing these are only partially supported by the different browsers. Here's some more information about that.

    programmatically:

    $('#myElement').attr('data-fruit', 'apple');
    // or
    document.getElementById('myElement').dataset.fruit = 'apple';
    

    Hidden Fields

    If you want to do things the old browser-compatible way and stuff the metadata directly into your html, you can use hidden fields. It's a bit cruder but easy enough to do.

    
    

    You can easily use jQuery selectors to query your list and find html blocks that contain user items that have the relevant hidden fields that match the metadata you are querying for.

提交回复
热议问题