1

我无法更改此脚本中的 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>
4

1 回答 1

-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̶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 W3school ) https://developer.mozilla.org/en/docs/DOM/element.setAttribute

于 2013-04-08T14:01:19.317 回答