2013-04-08 72 views
1

我无法更改此脚本中的href。但是innerHTML起作用。哪里不对?通过javascript更改href

<script> 
     FB.init({ 
      appId: 1234, 
      cookie: true, 
      status: true, 
      xfbml: true 
     }); 
     FB.getLoginStatus(function(response) { 
      if (response.status === 'connected') { 
       var uid = response.authResponse.userID; 
       var accessToken = response.authResponse.accessToken; 
       document.getElementById('test').href = 'http://www.example.com/auth/login'; 
       // document.getElementById('index-facebook-login-button').innerHTML = '<a class="index-facebook-login-button" href="http://www.example.com/auth/login" target="_self"></a>'; 

      } else if (response.status === 'not_authorized') { 
       document.getElementById('test').href += 'http://www.example.com/connectfacebook'; 
       //this works!!!      
       //document.getElementById('index-facebook-login-button').innerHTML = '<a class="index-facebook-login-button" href="http://www.example.com/connectfacebook" target="_self"></a>'; 

      } else { 
       document.getElementById('test').href += 'http://www.example.com/connectfacebook'; 
       //this works!!!      
       // document.getElementById('index-facebook-login-button').innerHTML = '<a class="index-facebook-login-button" href="http://www.example.com/connectfacebook" target="_self"></a>'; 
      } 

     }); 
    </script> 

<div id="index-facebook-login-text" onLoad="FB.getLoginStatus();"> 
some text here 
    <div id="index-facebook-login-button" style="margin-left: 25px;"> 
      <a id="test" class="index-facebook-login-button" href="" target="_self"></a> 
    </div> 
</div> 
+3

也许此刻的你正在尝试访问元素,它不存在或没有该ID?设置一个断点,检查DOM结构......通常的调试过程。 – 2013-04-08 13:59:32

+0

为什么'href + ='在第二和第三种情况下?没有什么意义(除非当前的URL已经有一个空的参数了) – CBroe 2013-04-08 13:59:33

回答

-1

在Javascript中的DOM API Element对象的属性是不一样的DOM的实际元素的属性。这个对象只是DOM的一个接口。要使用setAttribute()方法:

document.getElementById('test').setAttribute('href', 'http://example.com') 

HTTP:̶/̶/̶w̶w̶w̶.̶w̶3̶s̶c̶h̶o̶o̶l̶s̶.̶c̶o̶m̶/̶j̶s̶r̶e̶f̶/̶m̶e̶t̶_̶e̶l̶e̶m̶e̶n̶t̶_̶s̶e̶t̶a̶t̶t̶r̶i̶b̶u̶t̶e̶.̶a̶s̶p̶(don't use W3schoolhttps://developer.mozilla.org/en/docs/DOM/element.setAttribute

+0

[w3fools](http://w3fools.com) – fernandosavio 2013-04-08 14:02:24

+0

*“Javascript DOM对象中的Element对象的属性是不一样的作为DOM中实际元素的属性。“*这让IMO有点困惑。是的,'href'与'getAttribute('href')'不同,但为了设置它,在这种情况下并不重要。 JavaScript的DOM API仍然遵循官方的DOM API及其HTML DOM扩展。 – 2013-04-08 14:24:39