通过javascript更改href

时间:2013-04-08 13:57:48

标签: javascript html

我无法更改此脚本中的href。但是innerHTML可行。有什么问题?

   <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>

1 个答案:

答案 0 :(得分:-1)

Javascript的DOM API中Element对象的属性与DOM中实际元素的属性不同。该对象只是DOM的接口。您想使用setAttribute()方法:

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

h̶t̶t̶p̶:̶/̶/̶w̶w̶w̶.̶w̶3̶s̶c̶h̶o̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶̶ don't use W3school