HTML element with variable

后端 未结 4 1811
鱼传尺愫
鱼传尺愫 2021-01-15 08:08

In jQuery I can create a HTML element with data:

$(\'\').data(\"field\", { i: i, j: j }).appendTo(\"body\");
<         


        
相关标签:
4条回答
  • 2021-01-15 08:17

    Use this javascript.

    <button type="button" id="mybutton" onclick="btn()" data-field= "{ i: thevalueofi, j: tthevalueofj }"></button>
    <script>
     function btn(){
       var mydata = document.getElementById("mybutton").getAttribute("data-field");
        alert("data-field");
        // alert(mydata);
     }
    </script>
    

    OR

    Use jQuery like this.

    <button type="button" id="mybutton" onclick="btn()" data-field= "{ i: thevalueofi, j: tthevalueofj }"></button>
    <script>
     function btn(){
       var mydata = jQuery("button#mybutton").attr("data-field");
        alert("data-field");
        // alert(mydata);
     }
    </script>
    
    0 讨论(0)
  • 2021-01-15 08:25

    I want to expand on Derek's comment, and on some of the other answers here to address the burning question.

    ok, but how can i use it?

    The data-* series of attributes are designed for storing a set of data as attributes on an HTML element, and it's designed in such a way so that you don't have to explicitly deal with data to JSON conversions yourself or store all the data in a single attribute.

    Instead of storing all your data in a single data-* attribute, store the data in individual attributes, like so:

    <div id="user" data-id="12345" data-name="James" data-role="developer" 
            class="users wrappers" >
         ...
    </div>
    

    Then, when you need to retrieve your data, you can retrieve it all at once with a simple JavaScript command:

    var userObj = document.getElementById("wrapper").dataset;
    
    console.info("user id = " + userObj.id); // prints "12345"
    console.info("name = " + userObj.name);  // prints "James"
    console.info("role = " + userObj.role);  // prints "developer"
    

    As you can see, non-data-* attributes, like the id and class, are not included in dataset, which makes it easy to extract only the data itself.

    Moreover, the userObj is similar to a pure JavaScript object, which I can confirm by stringifying it:

    console.info("Stringified JSON object = " + JSON.stringify(userObj)); 
        // prints '{"id":12345,"name":"James","role":"developer"}'
    

    However, truth be told, the object isn't a true JavaScript object but is in fact a DOMStringMap, which has limitations when it comes to nesting data, which we'll see below:

    void setDataAttr(
      in DOMString prop,
      in DOMString value
    );

    Parameters

    prop

    The property whose value is to be set.

    value

    The property's new value.

    Note that the above value is a DOMString, not an object.

    In your case, you're storing all of your data as a single, stringified JSON object on a single data-* field called data-field. This isn't incorrect, but it's slightly different, and may lead to more work for you. It may have different advantages and disadvantages in regards to readability, for instance, as well as the extra work converting the string to an object.

    In your case, to extract the data, you'd need to do this:

    <!-- Note the nested quotes. This is what it looks like in the Chrome Elements 
         inspector. In reality, the quotes inside must be escaped -->
    <div id="user" data-field="{"id":"12345", "name":"James", "role":"developer"}" 
            class="users wrappers" >
    
    var userString = document.getElementById("user").dataset.field;
    

    Except, here's where we begin to see holes in this methodology. The dataset.field value is not an object like it would be in the first example; instead, it's a string, and we must convert it to an object ourselves:

    var userObj = JSON.parse(userString);
    

    Now we can access the properties of the data represented by data-field:

    console.info("name = " + userObj.name);  // prints the name "James"
    

    Unlike a regular JSON object, which can contain nested JSON objects, the DOMStringMap is an object containing key/value pairs where the values are all strings. In short, any nested objects inside a value are represented as strings, not as an object, which means they must be converted to objects individually.

    Again, this isn't a bad thing, but it suggests that storing objects in a single element might be better reserved for more complex data structures where the object representation is more than just one level deep. In that case, we must convert from string to JSON, but we'd have a good reason to do so in that case, since the engine won't do those conversions for us beyond just one level of nesting.

    Try manipulating the data yourself from the Chrome JavaScript console, or the Firebug console, if you prefer Firefox. The console allows us to play around with different techniques in real-time and get a stronger feel for how a certain feature is supposed to work. Hope this helps!

    0 讨论(0)
  • 2021-01-15 08:39

    With .dataset:

    document.querySelector('button').dataset.field
    

    This isn't supported in all browsers, so you may need to find a polyfill (or use jQuery).

    0 讨论(0)
  • 2021-01-15 08:40

    If you want the html of a button which will have the same data available as the button you created, you'll have to use the html5 data attributes. i.e.

    <button data-field='{ "i": "thevalueofi", "j": "tthevalueofj" }'></button>
    

    and read it

     function btn(){
            var field = $('button').data("field");
            alert(field.i)}
     }
    

    with plain js

     function btn(){
            var field = JSON.parse(document.querySelector('button').getAttribute("data-field"));
            alert(field.i)}
     }
    
    0 讨论(0)
提交回复
热议问题