문제

I'm trying to find a "best" method for dynamically loading files, and other elements by using the new html 5 "data-" attribute for storage and then removing it when needed.

My Question:

How do I target the "data-" attribute and remove it thus leaving the remaining attribute name?

For example, this:

<!-- Custom CSS -->
<link rel="stylesheet" class="custom" data-href="css/mobile.css">

Would turn into this:

<!-- Custom CSS -->
<link rel="stylesheet" class="custom" href="css/mobile.css">



Edit: This entire experiment is for Responsive Design (ui/performance), I need to be able to load css files/ elements depending on device resolution. This will result in higher performance for smaller devices to prevent unnecessary data loading. I'm using enquire.js plugin (amazing btw), which allows you to have functions fire off when a media query is targeted. So in an effort to stay current I wanted to use the "data-" attribute to add/remove elements from the DOM depending on device resolution.

This tutorial by Christian Heilmann does just this: http://christianheilmann.com/2012/12/19/conditional-loading-of-resources-with-mediaqueries/

I'm trying to combine his technique with enquire.js

도움이 되었습니까?

해결책

Assuming you know how to get to your elements, enabling is a one liner:

$(element).attr("href", $(element).data("href"));

since the data-href does nothing, you don't need to remove it. Just mirror it as real href attribute. To invalidate, either invalidate the href attribute again:

$(element).attr("href", false);

or remove it altogether:

$(element).removeAttr("href");

And for <img> it's the same trick but with the string "src" instead of "href"

다른 팁

While I agree that it's worth questioning whether this is the correct way to approach this problem, from a technical stand-point this is how you access, remove, and add attributes on elements.

$('[data-attrName]').each(function() {
    var $el = $(this);
    var val = $el.attr('data-attrName');
    $el.removeAttr('data-attrName')
       .attr('attrName', val);
});

To replace all data-attributename attributes with attributename can be accomplished simply by looping over the data object.

$(element).each(function() {
    var 
        el = $(this),
        data = el.data();

        $.each(data,function(key,value) { el.attr(key,value); });
});

I'll point out what others have already pointed out, though - I think you have decided that this is what you need to do to accomplish something, when it probably isn't what you should be doing.

Try asking a question whose answer will solve your actual problem, not asking a question whose answer will solve the problem that you are experiencing when you are using it to try and solve another problem....I'll understand if you don't understand that last sentence.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top