Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何用JavaScript动态创建link标签到head里? #148

Open
Sogrey opened this issue Nov 12, 2019 · 1 comment
Open

如何用JavaScript动态创建link标签到head里? #148

Sogrey opened this issue Nov 12, 2019 · 1 comment

Comments

@Sogrey
Copy link
Owner

Sogrey commented Nov 12, 2019

jQuery:

function createLink(cssURL,lnkId,charset,media){ 
var head = $($('head')[0]),
    linkTag = null;
 
 if(!cssURL){
     return false;
 }
 
 linkTag = $('<link href="' + cssURL + '" rel="stylesheet" type="text/css" media="' + (media || "all") + '" charset="'+ charset || "utf-8" +'" />');
  
 head.append(linkTag);
}

javascript:

function createLink(cssURL,lnkId,charset,media){ 
    var head = document.getElementsByTagName('head')[0],
        linkTag = null;
  
 if(!cssURL){
     return false;
 }
    
 linkTag = document.createElement('link');
 linkTag.setAttribute('id',(lnkId || 'dynamic-style'));
 linkTag.setAttribute('rel','stylesheet');
 linkTag.setAttribute('charset',(charset || 'utf-8'));
 linkTag.setAttribute('media',(media||'all'));
 linkTag.setAttribute('type','text/css');
    linkTag.href = cssURL; 
 
    head.appendChild(linkTag); 
}
@Sogrey Sogrey added this to javascript in Web面经题 Nov 12, 2019
@Sogrey
Copy link
Owner Author

Sogrey commented Nov 12, 2019

#149

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Web面经题
javascript
Development

No branches or pull requests

1 participant