开发者

Browsers not observing changes to data-*, CSS attribute selector properties not rendering

开发者 https://www.devze.com 2023-04-06 03:10 出处:网络
Given this CSS: [data-myplugin-object=\"blue-window\"]{ background-color: #00f; } [data-myplugin-object=\"red-window\"]{

Given this CSS:

[data-myplugin-object="blue-window"]{
    background-color: #00f;
}

[data-myplugin-object="red-window"]{
    background-color: #f00;
}

And this jQuery:

$('[data-myplugin-object="blue-window"]').each(function(event){
    $(this).data({
        'myplugin-object': 'red-window'
    });
});

And this HTML snippet:

<div data-myplugin-object="blue-window">
    <p>Hello world</p>
</div开发者_运维知识库>

Now, one would expect that when the jQuery snippet is executed (properly deferred until page load is complete of course) my blue window (which does initially render as blue) would turn red.

Nope, it certainly does not; and using Firebug and Developer Tools in Firefox and Chrome respectively, I can't observe any changes to the data-* attributes.

In order for the browser (and DOM toolboxes for that matter) to observe changes, do I need to revert to .attr() or is there a workaround for this?


jQuery.data() attributes are not actually stored on the DOM object in jQuery. The DOM object is tagged with a unique jQuery ID and the actual data is stored in a separate javascript data structure. Among other reasons, jQuery does it this way to prevent circular reference memory leak bugs that can happen in some browsers when data values are references to other DOM objects.

If you want to change the actual DOM attribute, I'd suggest setting the attribute directly yourself like this:

obj.attr("data-myplugin-object", "red-window");

Though, for what you're doing, I think most people would use adding/removing/changing CSS class names, not custom attributes as that is the common way of changing which CSS rules apply to an object.

<div id="myObj" class="blueWindow">
    <p>Hello world</p>
</div>

.blueWindow {background-color: #00F;}
.redWindow  {background-color: #F00;}

 $("#myObj").removeClass("blueWindow").addClass("redWindow");

Or if there are no other classes on the object:

 $("#myObj").attr("class", "redWindow");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号