2013-04-08 121 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