更改href =" favicon2.ico"在javascript中更改查询字符串时

时间:2013-06-11 11:09:12

标签: javascript

我在default.aspx

中的silverlight应用程序中有此代码
<head id="Head1" runat="server">   
  <link id="link1" rel="shortcut icon" href="favicon1.ico" type="image/vnd.microsoft.icon" />
  <title id="Title1" >hello</title>

我需要在更改查询字符串时更改JavaScript中的href="favicon2.ico"

我试着写这个,但它不起作用:

<script type="text/javascript">
  if( Request.QueryString ("user"). Equals("true", StringComparison.OrdinalIgnoreCase)) {
    document.title="hi user"; 
    document.getElementById('link1').href = ('favicon2.ico');
  }
</script>
</head>
</html>

2 个答案:

答案 0 :(得分:0)

尝试在代码中替换它

document.getElementById('link1').href = "favicon2.ico";

答案 1 :(得分:0)

添加JavaScript功能

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

将您的代码更改为纯JavaScript(您正在混合使用C#和JavaScript)

if(getParameterByName("user").toLowerCase() == "true")
{
   document.title="hi user"; 

   var newImage = new Image();
   newImage.src = 'favicon2.ico?_=' + new Date().getTime();
   document.getElementById('link1').href = newImage.src;    
}

更新

if(getParameterByName("user").toLowerCase() == "true")
{
   document.title="hi user"; 
   changeFavicon('favicon2.ico');
}

function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('link1');
link.id = 'link1';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
    document.getElementsByTagName('head')[0].removeChild(oldLink);
}
document.getElementsByTagName('head')[0].appendChild(link);
}