jquery获取动态跨度id值

时间:2015-01-01 16:08:41

标签: javascript jquery html dynamic

我在我的web项目中添加了facebook SDK,我通过id打印所有值,但我有一个疑问。如何通过jquery或javascript获取动态id值。

我的代码

  FB.api('/me', function(response) {
    console.log('Successful login for: ' + response.name);      
    var fullname = document.getElementById('admin_name').innerHTML = response.name;
});

//通过html显示

<span id="admin_name"></span>并且它已成功打印。

但是当我想通过jquery或javascript获取id值时,它会变为null或为空。

// Jquery Code

$(document).ready(function () {
   var adminName = $("#admin_name").text();
   alert(adminName);
});

我完全登录为Facebook代码

function statusChangeCallback(response) 
{
   console.log(response);   
  if (response.status === 'connected') {
      testAPI();
  } 
}
function checkLoginState() {
   FB.getLoginStatus(function(response) {
   statusChangeCallback(response);
  });
}
window.fbAsyncInit = function() {FB.init({
 appId      : '12345678910',
 cookie     : true,  
 xfbml      : true,  
 version    : 'v2.2' 
});
FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
};
// Load the SDK asynchronously
(function(d, s, id) {
   var js, fjs = d.getElementsByTagName(s)[0];
   if (d.getElementById(id)) 
       return;
       js = d.createElement(s); 
       js.id = id;
       fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
function testAPI() {
    FB.api('/me', function(response) {
      var fullname = document.getElementById('admin_name').innerHTML = response.name;
    });
}

并通过FB登录按钮调用

<fb:login-button max_rows="1" 
    size="large" 
    show_faces="false" 
    auto_logout_link="false"  
    onlogin="checkLoginState();">Login with Facebook
</fb:login-button>

1 个答案:

答案 0 :(得分:1)

你的问题是时间问题。 dom将抓住目前的价值,而不是即将到来的价值。在调用$(document).ready时,您的FB.api没有。因此,它将返回null。 调用FB.api后调用函数

编程:

alert代码粘贴在函数

alertMe = function(){
    $(document).ready(function () {
       var adminName = $("#admin_name").text();
       alert(adminName);
    });
}

并在FB API完成其事务时调用该函数

FB.api('/me', function(response) {
    console.log('Successful login for: ' + response.name);      
    var fullname = document.getElementById('admin_name').innerHTML = response.name;
    alertMe(); //send the call for the alert
});