[英]jquery get dynamic span id value
我在我的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代碼
$(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>
您的問題是時機之一。 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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.