最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does the data("key", value) method set data- attributes? - Stack Overflow

programmeradmin1浏览0评论

Will the jQuery $("..").data("key", value) method set the data-key attribute if one is present?

Adam Freeman's Pro jQuery states that it does:

Tip The data method takes the data attributes into account when setting values as well. When you specify a key, such a [sic] product, the data method checks to see whether there is a corresponding HTML5 data attribute, such as data-product. If there is, then the value you specified is assigned to the attribute. If not, then the data is stored internally by jQuery.

But I thought that it didn't, and the test that I ran implies that it doesn't. (I checked the errata section—nothing)

Full code is below, but the short of it is that when I set the data-name attribute by calling the attr method, the attribute value changes and can be seen in the chrome elements tab, and retrieved into newValue. When I set it with the data method, neither of these conditions are satisfied; it seems as though using data() always sets the value internally and never on the attribute, even if one is present.

Unfortunately, the docs' only mention of html5 data-attributes is in the section of the data method that takes only a key, and returns the conitant value; the description of data("key", value) doesn't seem to mention html5 data-attributes at all.


<html xmlns="">
<head>

    <script type="text/javascript" src=".7.0/jquery.js"></script>

    <script type="text/javascript">
        $(function () {
            var oldValue = $("#d").data("name");
            alert("old value " + oldValue);

            $("#d").data("name", "Adam");
            //$("#d").attr("data-name", "Adam");

            var newValue = $("#d").attr("data-name");
            alert("new value " + newValue);
        });
    </script>
</head>
<body>
    <div id="d" data-name="none"></div>
</body>
</html>

Will the jQuery $("..").data("key", value) method set the data-key attribute if one is present?

Adam Freeman's Pro jQuery states that it does:

Tip The data method takes the data attributes into account when setting values as well. When you specify a key, such a [sic] product, the data method checks to see whether there is a corresponding HTML5 data attribute, such as data-product. If there is, then the value you specified is assigned to the attribute. If not, then the data is stored internally by jQuery.

But I thought that it didn't, and the test that I ran implies that it doesn't. (I checked the errata section—nothing)

Full code is below, but the short of it is that when I set the data-name attribute by calling the attr method, the attribute value changes and can be seen in the chrome elements tab, and retrieved into newValue. When I set it with the data method, neither of these conditions are satisfied; it seems as though using data() always sets the value internally and never on the attribute, even if one is present.

Unfortunately, the docs' only mention of html5 data-attributes is in the section of the data method that takes only a key, and returns the conitant value; the description of data("key", value) doesn't seem to mention html5 data-attributes at all.


<html xmlns="http://www.w3/1999/xhtml">
<head>

    <script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.7.0/jquery.js"></script>

    <script type="text/javascript">
        $(function () {
            var oldValue = $("#d").data("name");
            alert("old value " + oldValue);

            $("#d").data("name", "Adam");
            //$("#d").attr("data-name", "Adam");

            var newValue = $("#d").attr("data-name");
            alert("new value " + newValue);
        });
    </script>
</head>
<body>
    <div id="d" data-name="none"></div>
</body>
</html>
Share Improve this question edited Apr 16, 2012 at 21:54 Adam Rackis asked Apr 16, 2012 at 21:49 Adam RackisAdam Rackis 83.4k57 gold badges278 silver badges400 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

I think that Adam Freeman's description is incorrect, or at least not pletely accurate.

According to the jQuery documentation:

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

This implies that jQuery pulls these attributes into its own internal representation, rather than overriding the values in the actual attributes.

A quick perusal of the code suggests the same.

According to jQuery's .data() method documentation:

Note that this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties.

It seems it uses the data= if it's there and doesn't throw an error.

Take a look for yourself:

function dataAttr( elem, key, data ) {
    // If nothing was found internally, try to fetch any
    // data from the HTML5 data-* attribute
    if ( data === undefined && elem.nodeType === 1 ) {

        var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();

        data = elem.getAttribute( name );

        if ( typeof data === "string" ) {
            try {
                data = data === "true" ? true :
                data === "false" ? false :
                data === "null" ? null :
                jQuery.isNumeric( data ) ? +data :
                    rbrace.test( data ) ? jQuery.parseJSON( data ) :
                    data;
            } catch( e ) {}

            // Make sure we set the data so it isn't changed later
            jQuery.data( elem, key, data );

        } else {
            data = undefined;
        }
    }

    return data;
}

jQuery's .data() function doesn't interact with the HTML5 data-* attributes at all, other than taking the initial values from them; I'm not entirely sure when this is done, though - another answer suggests it's done at the first call to .data(), which may be correct (it definitely makes sense).

Using .attr() to specify a new value for a data-* attribute doesn't modify the value that jQuery has stored to access using .data(). To illustrate, take a look at this jsFiddle. If you inspect the <div> element and then click on the button, you can see that whilst the attribute on the element has its value changed the two console.log() calls output the same value.

发布评论

评论列表(0)

  1. 暂无评论