Javascript 如果变量为空,则don';显示关联的HTML
我正在开发PhoneGap iOS Facebook应用程序,并正在显示用户的新闻源。以下是我目前的代码:Javascript 如果变量为空,则don';显示关联的HTML,javascript,facebook-graph-api,cordova,Javascript,Facebook Graph Api,Cordova,我正在开发PhoneGap iOS Facebook应用程序,并正在显示用户的新闻源。以下是我目前的代码: <script> function showPosts() { FB.api('/me/home', function(response) { console.log(response); if (!response.error) { var markup = ''; var messa
<script>
function showPosts() {
FB.api('/me/home', function(response) {
console.log(response);
if (!response.error) {
var markup = '';
var messages = response.data;
for (var i = 0; i < messages.length && i < 5; i++) {
var message = messages[i];
markup += '<p><img src="' + message.picture + '">' + message.message + '<img src="https://graph.facebook.com/' + message.from['id'] + '/picture">' + message.from['name'] + '</p><br>';
}
document.getElementById('newsfeedposts').innerHTML = markup;
}
});
}
</script>
函数showPosts(){
FB.api('/me/home',函数(响应){
控制台日志(响应);
如果(!response.error){
var标记=“”;
var messages=response.data;
对于(var i=0;i
';
}
document.getElementById('newsfeedposts')。innerHTML=标记;
}
});
}
现在,如果帖子中没有消息,将显示“undefined”。此外,当没有消息图片时,会出现一个空的图像图标,因为
post消息也是如此。如果message.message
为空,我是否可以创建一个If语句,说明没有消息时不显示任何内容,从而消除“未定义”
如果If语句有效,我应该将其放置在哪里?我尝试在“标记”中放置if语句,但无法使其工作 非常简单:
if (typeof message.picture != 'undefined') {
// message.picture is not empty, so do the stuff inside of here.
}
由于
消息
将始终存在,并且图片
在消息
中,因此即使图片
未定义,也不会引发错误。因此,您可以这样做:
if (message.picture) {
//Do things here.
}
谢谢你的帮助。如何将其与message.message变量也为空合并?我可以在“markup+=…”行的I端添加if starements吗?