我正在使用pubnub流API将对象"text":"Hey! my chat text here"
传递到DOM中的div标签中。我的问题是undefined
在"text":"Hey! my chat text here"
内连接到频道时没有<div id="textbox"></div>
的每个对象都会显示。我该如何摆脱undefined
?
undefined
undefined
undefined
Hey, my chat text
undefined
undefined
undefined
undefined
javascript代码
<script src="http://cdn.pubnub.com/pubnub-3.7.15.min.js"></script>
<script charset="utf-8">
PUBNUB.bind('load', window, function frontpageDemo() {
var PUBNUB_demo = PUBNUB.init({
subscribe_key: 'subkey_here',
});
PUBNUB_demo.subscribe({
'channel': "my_channel_here",
'connect': function(c) {
console.log('CONNECTED to ' + c);
},
'callback': function(m, a, subscribed_channel, c, real_channel) {
console.log(JSON.stringify(m));
console.log(JSON.stringify(subscribed_channel));
console.log(JSON.stringify(real_channel));
document.getElementById('textbox').innerHTML = '<div>' + m.text + '</div>' + document.getElementById('textbox').innerHTML;
}
})
});
</script>
答案 0 :(得分:2)
好的,我修复了这个问题,显然我需要if
和else
声明
PUBNUB_demo.subscribe({
'channel': "my_channel_here",
'connect': function(c) {
console.log('CONNECTED to ' + c);
},
'callback': function(m, a, subscribed_channel, c, real_channel) {
console.log(JSON.stringify(m));
console.log(JSON.stringify(subscribed_channel));
console.log(JSON.stringify(real_channel));
if (m.text === undefined) {}
else {document.getElementById('textbox').innerHTML = '<div>' + m.text + '</div>' + document.getElementById('textbox').innerHTML;
}
})
有关MDN undefined objects的更多信息